views:

3069

answers:

3

My class has an NSArray that is filled with objects. In my dealloc method, can I simply call release on my NSArray, or do I need to iterate the array and release all objects first?

+16  A: 

You can call release directly on the NSArray. The implementation of NSArray will take care of sending release to all the objects stored in the array.

Marc W
Should add: if you have a retain count on one of the contained objects, then you should autorelease *before* you add it to the array.
Matt Gallagher
I'm confused. Why must I autorelease *before* adding it to an array? Can't I, for example, explicitly do a 'release' after adding it to the array?e.g.[arrayObject addObject:myObject];[myObject release];
Heng-Cheong Leong
@Heng-Cheong Leong yes, that is also acceptable. The point is not to risk your object being dealloc'd before it is retained by the array.
Roger Nolan
That sounds contradictory to what I just read in the following blog:http://memo.tv/memory_management_with_objective_c_cocoa_iphoneHe says that adding an object to an array increases the reference count. So, instantiating it gives me one, adding to an array gives me two. If this is correct, releasing my NSArray will decrement ref count by 1, and I still need to explicitly call release as well. Is this incorrect?
Rich
That is not incorrect. But it also doesn't mean you need to iterate through the array and release all the objects yourself. If you do what Heng-Cheong said and release the object right after adding it to the array, you won't run into this problem. You just have to be aware that adding an object to a collection increases the retain count by 1, and releasing that collection (or removing the object from that collect, assuming it's a mutable collection) decreases the retain count by 1.
Marc W
+1  A: 

You should be able to just release the NSArray, and it will release all its objects, regardless of whether you're holding other references to them. If you have an instance object that also exists in the NSArray, you will have to release that object explicitly - just releasing the NSArray may not dealloc the object outside of the array context.

Tim
dealloc'ing an NSArray will *always* release all its objects, regardless of other references (which may or may not cause them to be immediately dealloc'd depending on other references); you are conflating "release" and "dealloc".
smorgan
Thanks - edited to correct.
Tim
+2  A: 

NSArray retains objects when they're added, and releases them when they're removed or the array is deallocated. Keep this in mind, it's this concept of "ownership" that retain/release memory management is built upon. It's the same with the object that owns the array, if it also retained the objects in the array you will need to send them another release message in your dealloc implementation. If not, and if no other objects retained them, they'll be deallocated once the array releases them.

Marc Charbonneau