0
votes

I've a NSMutableArray in AppDelegate I'm using property (nonatomic,retain) and synthesizing it

again in didfinishlaunch allocating it using [[nsmutablearray alloc]init];

So, my doubt is if I'm releasing it in deallloc using release method. is it released properly? or still retain count is there. if I'm doing wrong kindly provide a proper solution.

5
If this is a new project, turn on ARC.bbum

5 Answers

4
votes

It depends on how you're assigning it. If your assignment is directly to the ivar, like

myProperty = [[NSMutableArray alloc] init];

Then a single release in dealloc is adequate, because you have an expected retain count of 1 from the alloc.

On the other hand, if you have used a synthesized setter via either:

[self setMyProperty:[[NSMutableArray alloc] init]];

or

self.myProperty = [[NSMutableArray alloc] init];

then you have almost certainly leaked the object. You incremented the retain count twice (once via alloc and once in the setter) and only decremented it once (in dealloc).

Best IMO is to use the setter and the autorelease pool:

self.myProperty = [[[NSMutableArray alloc] init] autorelease];

Here the alloc is balanced with a local autorelease, and the setter`s retain is balanced with the dealloc release.

While that approach involves two extra methods (the setter method and the autorelease call), it ensures that any retained values that were formerly set in the the property are released as necessary (in the setter method).

0
votes

Yes, you still need to release it in dealloc. These two pages are must-reads for iOS/Cocoa developers regarding memory management

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

For your specific example, see the section on the second link called "Implement dealloc to Relinquish Ownership of Objects"

Here is also a link to this issue addressed on Stack Overflow: Understanding reference counting with Cocoa and Objective-C

0
votes

If you do something like:

my_property = [[NSMutableArray alloc] init];

The 'my_property' assumes ownership of your array. Your class's dealloc method has to release the array to prevent leaks.

[my_property release];

-or-

self.my_property = nil;
0
votes

If you are using

[self setMutableArray:[[nsmutablearray alloc] init]];

in this case it will release any memory which is previously assigned to it(give up ownership). so in dealloc method you are simply writing

self.mutableArray = nil; 

then it will give up the ownership and memory allocated to mutableArray will be released automatically

0
votes

In your case the retain count will be 2 and the array keeps releasing. When you have set the property you do not need to initialise it .