[Solved] Regarding retain count [closed]


Retain counts are pretty much useless, see http://whentouseretaincounts.com for details of why.

However, I added calls to retainCount to your code and ran the following:

NSArray *arr = [[NSArray arrayWithObjects:@"ag", @"sdfg", @"dgh", nil] retain];
NSLog(@"%ld", [arr retainCount]);

NSArray *newArr = [[arr mutableCopy] retain];
NSLog(@"%ld", [newArr retainCount]);

[arr release];
NSLog(@"%ld", [arr retainCount]);

[newArr release];
NSLog(@"%ld", [newArr retainCount]);

newArr = [NSArray arrayWithObject:@"sdfdhs"];
NSLog(@"%ld", [newArr retainCount]);

and got the following results:

2013-01-24 15:45:56.840 Untitled 2[96774:707] 2 
2013-01-24 15:45:56.842 Untitled 2[96774:707] 2 
2013-01-24 15:45:56.842 Untitled 2[96774:707] 1 
2013-01-24 15:45:56.843 Untitled 2[96774:707] 1 
2013-01-24 15:45:56.843 Untitled 2[96774:707] 1

The first result is 2 not 1 because the return value from arrayWithObjects has been autoreleased but hasn’t actually been released yet because the autorelease pool has not been flushed yet (this usually happens in the event loop).

The second result is 2 because the mutableCopy returned a retained object and we are retaining it again.

The third result is 1 because we release arr which had a retain count of 2. Still haven’t flushed the autorelease pool.

The fourth result is 1 because we released newArr which had a retain count of 2.

The final result is 1 because we leaked the contents of newArr and assigned a new autoreleased array to the variable. The retain count of 1 is the not yet autoreleased count.

However, retain counts should not be trusted. Learn the memory management rules (whether you are using ARC or not).

solved Regarding retain count [closed]