开发者

Correct way to clear/release an array of arrays

开发者 https://www.devze.com 2022-12-30 17:15 出处:网络
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?

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 开发者_如何学CremoveAllObjects];

(d) releasing the array

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

thanks in advance


(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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消