简体   繁体   中英

Crash when releasing image in UITableViewCell

I'm going through a tutorial on table views for iPhone. Below is a data source method for populating the table.

- (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;
}

I noticed that the author did not release the image after setting it as the icon for the table cell. The source code defining UITableCell.imageView.image does, in fact, show that it is a retained property. If I don't release my own copy of the image, the retain count would end up being 2 by the end of the method. So I decide to release it to free up memory. However, doing so, causes the iPhone emulator to crash when I swipe the table a little bit off the screen. Why?

The method imageNamed: is a convenience method. In other words, the image resource is autoreleased for you. If you try to release that image object, then you have over-released it.

Edit: The rule for memory management is as follows: Whenever you call alloc , new , copy , or retain , you must call release or autorelease .

The -imageNamed: method returns an autoreleased image. Thus, you do not need to release it yourself.

The line of code: cell.imageView.image = image; takes care of the retaining of the image that needs to be done.

Remember, you should only call release or autorelease on an object if you called retain on it or created it with alloc , or a method with the word "new" or "copy" in it. In all other cases (assuming they are doing things correctly, which you have to assume they are), the object that is returned is autoreleased.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM