2012-04-02 18 views
0

我有泄漏自定义单元格的问题。泄漏自定义单元格

在我重写的UITableViewController,我有,

- (UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    TwitterTweetTableCell *cell = nil; 

    // Obtain the cell... 

    cell = [[TwitterTweetTableCell alloc] 
      initWithTable:tableView 
       andTweet:[[self getTimeline] objectAtIndex:indexPath.row]]; 

    return [cell autorelease]; 
} 

,并在相应覆盖的UITableViewCell类,

- (TwitterTweetTableCell *) initWithTable:(UITableView *) tableView 
    andTweet:(NSDictionary *) tweet 
{ 

    tweetCell = nil; 

    // ************************************************************************************ 
    // The identifier used in the following dequeue is the one set in the corresponding nib 
    // ************************************************************************************ 

    tweetCell = (TwitterTweetTableCell *) 
     [tableView dequeueReusableCellWithIdentifier:@"tweetCell"]; // <-- set this in NIB 

    if (tweetCell) 
    { 
     NSLog(@"tweetCell: Reuse!"); 
    } 

    if(!tweetCell) 
    { 
     NSArray *topLevelObjects = [[NSBundle mainBundle] 
       loadNibNamed:@"TwitterTweetTableCell" owner:nil options:nil]; 

     for(id currentObject in topLevelObjects) 
     { 
      if([currentObject isKindOfClass:[TwitterTweetTableCell class]]) 
      { 
       tweetCell = (TwitterTweetTableCell *)currentObject; 

       break; 
      } 
     } 

     // yadda, yadda, yadda 

     [tweetCell retain]; 
    } 

    return tweetCell; 
} 

有一个相应的NIB自定义单元格(TwitterTweetTableCell),并且指出在代码中,单元的标识符在那里设置为'tweetCell'。

代码工作,除了罚款,根据仪器,它泄漏细胞:-(

我相信我在小区为1的retainCount返回正确的(这是从页头返回而且,不管怎么说,如果我不将其与僵尸崩溃)。由于代码显示,我后来终于交给受表控制器之前自动释放它。

为什么这泄漏将不胜感激思考。

回答

0

问题这里是cellForRowAtIndexPath:你正在为你的自定义单元的新实例分配内存,但是在你的c的初始化程序中ustom单元格,你永远不会使用你分配的内存,因为你不返回self,而是返回一个可重用的现有单元或从一个nib实例化一个新单元。

既然你是initWithTable:andTweet:方法并不是一个真正的初始化器,你应该把它改为一个方便的方法,它会返回自动释放的实例。更改方法签名,

+ (TwitterTweetTableCell *) cellWithTable:(UITableView *) tableView 
andTweet:(NSDictionary *) tweet 

让它自动释放它的返回值,

return [tweetCell autorelease]; 

,然后作出它一个稍微不同的呼叫cellForRowAtIndexPath:,你将所有设置:

return [TwitterTweetTableCell cellWithTable:tableView 
            andTweet:[[self getTimeline] objectAtIndex:indexPath.row]]; 
+0

优秀!非常清楚,有启发性,最重要的是,它已经解决了这个问题。我从中学到了很多 - 谢谢你,yuji。 – Snips 2012-04-02 17:16:05