Question

This is my code:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *string = [[NSString alloc] initWithFormat:@"s"];

[string autorelease];
NSLog(@"retainCount of string is %d", [string retainCount]);

[pool release];
NSLog(@"retainCount of string is %d", [string retainCount]);

When I try to understand autorelease and release, I'm confused. if use [string autorelease], after senting a release message to pool, retainCount of string is still 1. But use [string release] to replace the [string autorelease], finally retainCount of string will be 0. What I know about autorelease is "add an object to the current autorelease pool for later release by sending it an autorelease message". Why I sent it an autorelease message and release the pool, I still can access the object.

Was it helpful?

Solution

Here's the thing: the retainCount is an implementation detail. You can never rely on it being any specific value. All you really need to think about is whether you own an object or not.

After you allocate the string, you own it. When you autorelease the string, you no longer own it and it could disappear when you drain/release the autorelease pool. If nobody else owns it, it will disappear when you release the autorelease pool. Anywway, you can't legitimately send the string messages after you have released the autorelease pool.

In the current implementation, the string is created with a retain count of 1. The autorelease does not change the retain count. When the pool is released, release is sent to all the objects in it, that includes your string. The code in release looks something like this:

if (retainCount == 1)
{
    [self dealloc];
}
else
{
    retainCount--;
}

So you can see that the retain count will never go down to zero. Your final NSLog works because the memory used by the string has not yet been recycled.

OTHER TIPS

You have to use [pool drain] instead of release message to release all autoreleased objects in the pool. This message will call [pool release] for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top