在UITableViewCell中释放图像时崩溃

时间:2011-04-17 03:11:12

标签: iphone objective-c memory-management

我正在浏览iPhone的桌面视图教程。下面是填充表的数据源方法。

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
    static NSString* SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [listData objectAtIndex:row];
    UIImage* image = [UIImage imageNamed:@"face.png"];
    cell.imageView.image = image;
    //[image release];
    return cell;
}

我注意到作者在将其设置为表格单元格的图标后没有释放图像。事实上,定义UITableCell.imageView.image的源代码确实表明它是一个保留属性。如果我没有发布我自己的图像副本,则保留计数最终会在方法结束时为2。所以我决定释放它以释放内存。但是,这样做会导致iPhone模拟器在我将屏幕滑动一点时崩溃。为什么呢?

2 个答案:

答案 0 :(得分:2)

方法imageNamed:是一种方便的方法。换句话说,图像资源为autoreleased。如果您尝试释放该image个对象,那么您已经过度释放它。

修改:内存管理规则如下:每当您拨打allocnewcopyretain时,必须致电releaseautorelease

答案 1 :(得分:1)

-imageNamed:方法返回自动释放的图像。因此,您不需要自己发布它。

代码行:cell.imageView.image = image;负责保留需要完成的图像。

请记住,如果您在对象上调用retain或使用alloc创建了对象,或者在其中使用了“new”或“copy”一词的方法,则应该只调用对象的释放或自动释放。在所有其他情况下(假设它们正确地执行操作,您必须假设它们是这样),返回的对象是自动释放的。

相关问题