views:

84

answers:

2

And again my array of arrays ....

When I have an array "x" that contains multiple instances of an array "y", how do I clear/release it without risking memory leaks?

are the following calls sufficient?

(a) clearing the array

[x removeAllObjects];

(b) releasing the array

[x release];

or do I need to enumerate the array, such as:

(c) clearing the array

for(int i=0;i<x.count;i++)
    [[x objectAtIndex:i] release];
    [x removeAllObjects];

(d) releasing the array

for(int i=0;i<x.count;i++)
    [[x objectAtIndex:i] release];
    [x release];

thanks in advance

+6  A: 

(b) Should suffice. The array's deallocator will release all contained objects, with a release for every retain (so multiple instances will be released as many times as they were added).

Never do [[x objectAtIndex:i] release] -- you haven't retained the returned object, so you will muck up its retain count by releasing it.

walkytalky
iFioh: (a) and (b) are valid; (c) and (d) are not (they over-release the objects in the array, which will cause crashes). If you want to keep the array in order to put objects into it later, use (a). If you want to dispose of the array entirely (as in `dealloc`), use (b).
Peter Hosey
A: 

The best way to make sure no memory leak is that after you add that object to an array, you should release it so that the retain count of an object is 1 and only the array holds the retain of it. So that, when you release the array, it will send release message to all objects in the array and the retainCount of all objects will become 0 and they will be dealloc

vodkhang
The retain count might or might not be 1 once the object is added to the array. You might or might not need to release it upon addition to the array. Finally, the objects might or might not be deallocated upon removal of the array. Never consider the retain count as an absolute value, only something you change. The retain count of an object at any given time is an implementation detail often beyond your control.
bbum
Maybe you misread it, but I don't say that when it is removed from the array, it will be deallocated. I just mean that if you remove it out and it gets retainCount 0, it will be dealloc (not immediately, but in sometime, and depends on the system as well). Anyway, I think it should just be a good practice, and to remind people that when they add an object into an array, the retainCount will be incremeneted, so if they want to make sure only array holds that object, they should release that object
vodkhang
@vadkhang: the point is that if you are even thinking in terms of retainCount, you are doing it wrong. You should think only in terms of ownership. For instance, in d above, if you ask "do I own a reference I obtained from objectAtIndex: ? The answer is "no" so it's clear that the release inside the loop is incorrect.
JeremyP
Apologies for mis-spelling your name.
JeremyP