开发者

Objective-c NSMutableArray release behaviour

开发者 https://www.devze.com 2023-01-29 19:58 出处:网络
Does the release, recursively releases all i开发者_StackOverflownner objects? or must it be done manualy?

Does the release, recursively releases all i开发者_StackOverflownner objects? or must it be done manualy?

Can I do just this?

NSMutableArray *list = [[NSArray alloc] init];
// ...
// fill list with elements
//...
[list release];

Or must I release all inner objects one by one before releasing the NSMutableArray? // Suposing there isn't any other reference to the contained objects, except on the list itself.


Yes it does. It retains them when added, and releases them when dealloc'd. This is actually one of the most common questions I see here.


If you are owning the object then you will have to release it.

    NSMutableArray *list = [[NSArray alloc] init];

    NSString *str = [[NSString alloc] init] // you are the owner of this object
    [list addObject:str];
    [str release]; // release the object after using it
    [list release];

If you are not the owner of the object then you should not release.

    NSMutableArray *list = [[NSArray alloc] init];

    NSString *str = [NSString string]; // you are not owning this object
    [list addObject:str]; // str retain count is incremented
    [list release];  // str retain count is decremented.

This is the concept which even array also uses. When you add any object to the array, array will retain it. In the sense it becomes the owner of that object and It will release that object when you release the array.

0

精彩评论

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