Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray memory management

NSMutableArray *a1 = [[NSMutableArray alloc] init];
NSMutableArray *a2 = [NSMutableArray array];

TempObj *obj = [[TempObj alloc] init]; //assume this line is repeated for each obj
[a1 addObject:obj];
[a1 addObject:obj2];
[a1 addObject:obj3];
[a1 addObject:obj4];

[obj release];
[obj2 release];
[obj3 release];
[obj4 release];

[a1 release];

Ok so a2 is an autorelease obj so I don't have to call release on it? Also how do you know when you get an autorelease object?

And for a1, I don't have to loop through the array and release each object first? What if I called [a1 removeAllObjects]; does that call [[a1 objectAtIndex:#] release];

Am I supposed to release those objects after I've added them to the array?

like image 842
chicken Avatar asked Jan 19 '09 00:01

chicken


2 Answers

When you add an object to an array, it calls retain on that object. If you don't release your pointer to that object, it will be a leak. When you release the array, it will call release on all of the objects that it holds, since it called retain previously.

As for autorelease vs release, the only way to know for sure (aside from possibly reading the documentation) is by the name of the method. I believe the rule in general is that if you didn't allocate the object, then you aren't responsible for releasing it.

Regarding the object creation methods, all of the convenience methods (array:, arrayWithObjects:, arrayWithArray:, etc.) return autoreleased objects. However, their corresponding init methods (init:, initWithObjects:, initWithArray:, etc.) do not - if you call them, you are responsible for calling release on the returned object.

I seem to recall a few other questions on this topic here - you might try searching around for a more thorough explanation.

like image 188
Andy Avatar answered Nov 17 '22 05:11

Andy


It's easier to think of Objective-C memory management as ownership rather than in terms of retain-release. When you add the objects to the array, the array is now a co-owner of the object and is responsible for properly managing the memory. When the owner (whatever object contains the code you posted) calls release on the objects, it's giving up ownership and now the array is the sole owner.

Apple has a good primer on how ownership works in Cocoa (including how you know when you are responsible for calling release on an object): Memory Management Programming Guide For Cocoa. It's a must-read if you want to use Cocoa.

like image 22
Chuck Avatar answered Nov 17 '22 06:11

Chuck