开发者

iOS Development: How am I mismanaging memory in this code?

I just added some code that was taken from the Apple docs which shows how to use custom UITableViewCells that are created from a nib. I'm new to iOS development, so I'm still learning about proper memory management and the code isn't exactly clear to me as to how it works in the first plac开发者_JAVA百科e. When I run the Allocations instrument, it shows unallocated memory in the code below. Specifically, it shows the UITableViewCells remain alive after the view controller is popped off the nav stack...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{    
    static NSString *CellIdentifier = @"MyCustomCellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell_iPhone" owner:self options:nil];  //<--Allocations instrument complaining about this line
        cell = customCell;
        [self setCustomCell:nil];
    }

    return cell;
}

customCell is an instance var defined in this view controller, like so...

IBOutlet UITableViewCell *customCell;
@property (nonatomic, retain) IBOutlet UITableViewCell *customCell;

Is there a problem in this code?

Thanks so much for your wisdom!


I compared the code from the documentation:

if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"TVCell" owner:self options:nil];
    cell = tvCell;
    self.tvCell = nil;
}

With your code:

if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell_iPhone" owner:self options:nil];
    cell = [self customCell];
    [self setCustomCell:nil];
}

There seems to be a disparity at the line where you assign cell. Apple's example code uses tvCell, the instance variable, whereas you use [self customCell], the property getter for the instance variable. Could that be the cause? Try changing

    cell = [self customCell];

to

    cell = customCell;


Your code looks good to me, as far as memory is concerned.

What I think is happening is that your view controller is not being released. In ObjectAlloc, you see the table cells still being retained because they in turn are held by your table view, which in turn is being held by your view controller...

The most common reason why that would be, would be forgetting to set anything that uses your view controller as a delegate to nil in dealloc.

Or possibly, but more unlikely, you are not releasing your table view. In ObjectAlloc, after you leave the view controller, I would check to see if the view controller itself is also in memory.


Use the debugger. Set a break point in dealloc. Is it being called when you pop the nav controller?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜