开发者

NSMutableArray - memory management

just a short question: Does the NSMutableArray -addObject:(id)object method retain the object-parameter?

Thanks开发者_如何学编程


Yes, anything in a collection (set, array, dictionary) will be retained in the collection. That is of course if the collection is retained at the first place.

Once you add anything in a collection you need to release it if you are the owner.


Yes, it will retain the object. The object will be released when the array is released. If you're adding objects you've allocated to the array, make sure you release them once they've been added.

Object *o = [[Object alloc]init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:o];
[o release];
[array release];


Yes. It also releases all the objects in contains when it's retain count reaches zero.


The answer is, yes it does.

And in the future, here's how you can test for these situations. You can find out the retain count of an object using:

NSLog(@"Count: %d", [object retainCount]);

Use this code before and after adding the object to the array to see for yourself.

I must warn you though, a lot of people advise against using retainCount for anything. That being said, I think it's okay to use it to track increases and decreases in retaincounts for objects (like in my answer) but not much else.

Don't depend on retainCount values in your code; Just use the differences to track allocs and releases.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜