NSArray *arr = [[NSArray arrayWithObjects:@"ag", @"sdfg", @"dgh", nil] retain];
NSArray *newArr = [[arr mutableCopy] retain];
[arr release];
[newArr release];
newArr = [NSArray arrayWithObject:@"sdfdhs"];
What will retain count after each line? Please explain this to me. Thanking You…
Retain counts are pretty much useless, see http://whentouseretaincounts.com for details of why.
However, I added calls to
retainCountto your code and ran the following:and got the following results:
The first result is
2not1because the return value fromarrayWithObjectshas 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
2because themutableCopyreturned a retained object and we areretaining it again.The third result is
1because we releasearrwhich had a retain count of2. Still haven’t flushed the autorelease pool.The fourth result is
1because we releasednewArrwhich had a retain count of2.The final result is
1because we leaked the contents ofnewArrand assigned a new autoreleased array to the variable. The retain count of1is the not yet autoreleased count.However, retain counts should not be trusted. Learn the memory management rules (whether you are using ARC or not).