Search code examples
objective-cnsmutablearrayreleasedealloc

Why NSMutableArray element is not being deallocated?


Why NSMutableArray element is not being deallocated when it is added like this:

[map addObject:[[FLItem alloc] init]];

[map release];

and it works when:

FLItem *item = [[FLItem alloc] init];
[map addObject:item];
[item release]; 

[map release];   

What is the difference here?

P.S. There is NSLog in FLItem's dealloc implementation.


Solution

  • When you add the item like this:

    [map addObject:[[FLItem alloc] init]];
    

    or like this:

    FLItem *item = [[FLItem alloc] init];
    [map addObject:item];
    

    its retain count is 2 because you created it using init (that's 1) and the NSMutableArray also retains it (that's another 1).

    So when you release the array, it will release the item and its retain count becomes 1. So in the first case it doesn't get deallocated and in the second case where you call [item release]; it gets deallocated.

    What you should probably do in the first case is:

    [map addObject:[[[FLItem alloc] init] autorelease]];