views:

48

answers:

3

I'm new to objective C, I have a NSMutableArray with 3 objects in it, then I try to print the retainCount of the array. Why the final retainCount return -1? Thanks

NSLog(@"myArray has retain count of %d", [myArray retainCount]);    
[myArray release];
NSLog(@"myArray has retain count of %d", [myArray retainCount]);

Result from console:

2010-10-17 11:58:06.407 TestRetainCount [527:a0f] myArray has retain count of 1
2010-10-17 11:58:06.407 TestRetainCount [527:a0f] myArray has retain count of -1
+3  A: 

After an object has been deallocated (which may happen after a release), you can no longer rely on its data being intact. You're trying to trust the retain count after it has become invalid.

On a general note, don't use the retain count. Ever. Use the rules in the memory management programming guide, and you'll always get the reference counting correct.

Graham Lee
A: 

Can't rely on an accurate retainCount because of the timing autoreleased objects. That said, count your alloc/init, new, retains, etc... and match with corresponding release.

Jordan
There is no retain count in GC (at least not in ObjC terms). And, as Graham said, you can effectively never see a retain count of 0 because the object is already deallocated by that time.
bbum