Question

(sorry for my english :-) I'm loading a custom UITableViewCell:

static NSString *CellIdentifier = @"ReminderCell";
ReminderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    NSLog(@"Alloco nuova cella");
    NSArray *objectsInNib = [[NSBundle mainBundle] loadNibNamed:@"ReminderCell" owner:nil options:nil];
    for(id currentObject in objectsInNib)
    {
        if([currentObject isKindOfClass:[ReminderCell class]])
        {
            cell = (ReminderCell *)currentObject;
            break;
        }
    }
} //fine caricamento cella dal Nib

return cell;

I'm setting the owner to nil because I have .m and .h for this cell, and want to have the outlet inside it's own files and not in the UITableViewController. It's working ok.

My question is about correct memory management in this situation.

I understand that loadNibNamed returns an autoreleased array. Moreover, I understand that the autorelease pool is drained at the end of the current loop. For this reason, there should be no need to retain my custom cell before returning it.

But, I've heard many times that you shuold assume that an autoreleased object is guaranteed to live only until the end of the method where the autorelease was sent. Assuming this, I should retain the cell immediately and then autorelease it:

cell = [[(ReminderCell *)currentObject] retain];
//code...
[cell autorelease];
return cell;

Is this correct or should I not worry about this? Thanks

Was it helpful?

Solution

This is not necessary. Object is not guaranteed to live only until the end of the method where the autorelease was sent - methods are irrelevant here. Object will be released after autorelease pool to which it was added by autorelease method is drained. Since there is no autorelease pool management in your method currentObject will not receive release during its execution.

For example (without ARC of course):

id obj;
NSAutoreleasePool *pool = [NSAutoreleasePool new];
...
obj = [other object];
...
[pool drain];

[obj doSomething]; // DANGEROUS

In your case it is something like:

id obj;
...
obj = [other object];
...
[obj doSomething]; // SAFE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top