【问题标题】:Dealloc of custom cell loaded from NIB is not called未调用从 NIB 加载的自定义单元的 Dealloc
【发布时间】:2012-08-20 09:06:14
【问题描述】:

所以我有一个名为 MCProductCell 的子类 UITableViewCell,它是从 NIB 加载的。问题是当表格被释放时,我的自定义单元格的dealloc方法甚至没有被调用一次。

这里是一些示例代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"MCProductCellIdentifier";
    MCProductCell *cell = (MCProductCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
   // Boolean value needed to determine if it is a reused cell or not. If it's not reused we have 
   // to start the thread that loads the image. For reused cells, that thread is started at the
   // end of the scrolling
   BOOL recycled = YES;
   if (cell == nil) {
       NSLog(@"cell alloc");
       recycled = NO;
       NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MCProductCell" owner:self options:nil];
       cell = [nib objectAtIndex:0];
   }
   MCProduct *product = [products objectAtIndex:indexPath.row];
   cell.product = product;
   cell.cartViewController = self;
   cell.productImage = product.cachedThumbnailImage;
   if (product.cachedThumbnailImage == nil) {
       cell.productImage = [ViewControllerUtils getDefaultImage];
       if (!recycled)
           [NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:cell withObject:cell.product.imageThumbnailUrl];
   }

   return cell;

}

由于某种原因,当我第一次展示包含表格的 UIViewController 时,我的自定义单元格的 dealloc 方法称为 ONCE。 问题是,在 dealloc 方法中,我想将单元格作为观察者删除,如果不调用它,则不会将单元格作为观察者删除。 tableview 也是一个出口。

【问题讨论】:

    标签: iphone uitableview memory-management


    【解决方案1】:

    我想通了,一定是因为单元格的保留计数没有下降到 0。 这意味着您还有另一个保留。

    我更有经验的同事认为这是因为您使用的是 detachNewThreadSelector,它可能会保留单元格。

    他建议您使用某种类型的异步图像来加载图像,例如 https://github.com/nicklockwood/AsyncImageView/

    祝你好运。

    【讨论】:

    • 我已经评论了我创建新线程的所有行并且我遇到了同样的问题。还是谢谢你。
    • 也许还有其他地方保留了单元格?
    【解决方案2】:

    “cell.cartViewController”属性是如何定义的?如果它保留了您的控制器对象(self),那么您可能有一个保留周期!

    【讨论】:

    • 我在使用assign,调用了cartViewController的dealloc方法。
    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2012-08-07
    相关资源
    最近更新 更多