retainCount confusion


#1

On page 66 after obtaining an autoreleased instance of Possession, we read:

I think, this is not true. An autoreleased instance has already a retain count of one after being allocated and before being added to the array and a retain count of 2 after being added to the array.
Also, shortly after:

I think the conclusion is not true. After releasing the array its retain count goes to 0 and gets deallocated. The deallocation of the array implies the instances of Possession being released, so their retain counts go now to 1, but they are still alive. Actually, other pointer variables can still reference these living instances. Only when the pool gets drained will the retain count of these Possession instances go to 0 and will be finally deallocated.

Please look at the following slight modification of your code:

[code]int main (int argc, const char * argv[])
{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSMutableArray *items = [[NSMutableArray alloc] init];
Possession *firstPossesion = nil;
for (int i = 0; i < 10; i++) {
    Possession *p = [Possession randomPossession];
    if (i == 0) {
        firstPossesion = p;
        NSLog(@"retainCount before adding to array = %lu", [firstPossesion retainCount]);
        [items addObject:firstPossesion];
        NSLog(@"retainCount after adding to array = %lu", [firstPossesion retainCount]);
    }
    else {
        [items addObject:p];            
    }
}

[items release];    
items = nil;

NSLog(@"retainCount after releasing the array = %lu", [firstPossesion retainCount]);

[pool drain];

return 0;

}[/code]
And the result:
[Switching to process 17589 thread 0x0]
2011-10-10 16:31:50.273 RandomPossessions[17589:707] retainCount before adding to array = 1
2011-10-10 16:31:50.275 RandomPossessions[17589:707] retainCount after adding to array = 2
2011-10-10 16:31:50.277 RandomPossessions[17589:707] retainCount after releasing the array = 1
(gdb)


#2

Yes, the autorelease pool “owns” these objects. But for purposes of understanding ownership, this explanation serves well. The conclusion you came to is the desired conclusion and we’re glad you came to it. :slight_smile: