Reputation: 6337
I'm still shaky on the subtler aspects of memory management, and I have a question about the aggressive retaining/releasing I've seen in some sample code. Specifically:
- (void)loadContentForVisibleCells
{
NSArray *cells = [self.tableView visibleCells];
[cells retain];
for (int i = 0; i < [cells count]; i++)
{
// Go through each cell in the array and call its loadContent method if it responds to it.
FlickrCell *flickrCell = (FlickrCell *)[[cells objectAtIndex: i] retain];
[flickrCell loadImage];
[flickrCell release];
flickrCell = nil;
}
[cells release];
}
Why the [retain/release] cycle on the FlickrCell (lines 8 & 10)? The cell is in an NSArray which by definition has retained its contents (I think...?), and the NSArray itself is retained. Why would this additional retain be necessary?
Furthermore, why the retain on the NSArray returned by [self.tableView visibleCells] (line 3)? Isn't the array guaranteed to be around for the duration of this method call?
Thanks very much.
Upvotes: 2
Views: 89
Reputation: 69382
In this case the retain
/release
isn't required since the returned cell is actually auto-released. The same goes for the extra retain
/release
on the cells
array.
You can safely remove all retain
and release
calls from your code snippet to perform correct memory management.
Also note that this doesn't really have much of a performance penalty. the retain
and release
calls are simply incrementing and decrementing the retain count of the instance.
As a general rule, every time you call alloc
, copy
or retain
you should call release
or autorelease
. If you don't call alloc
, copy
or retain
then you don't need to use release
or autorelease
. All of the Cocoa methods (and all Objective-C frameworks for that matter) return auto-released object instance, so that this code doesn't have to look like your snippet.
If you want to know more about memory management in Objective-C I suggest reading over the Memory Management Programming Guide.
Upvotes: 2