I’ve created autorelease pool. localString has added to this pool. I released the pool. localString and string must be deallocated. But in reality they are still alive. You can see my log:
Why is the string object still alive? I don't know.
and code:
-(NSString*) happyString
{
NSString *localString = [[[NSString alloc] initWithString:@"I don't know."] autorelease];
return localString;
}
-(IBAction) onButton:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *string = [self happyString];
[pool release];
NSLog(@"Why is the string object still alive? %@", string);
}
Strings (
NSStringinstances and statically allocated strings with@"") are immutable in Cocoa, so when you try to create a newNSStringfrom a statically allocated one, theNSStringclass can make an optimisation: a newNSStringinstance is not created (the object created when you called-allocis immediately released), and the reference to your statically allocated string is returned. That is, the line:Is actually equivalent to:
(If you check the memory addresses of those two objects, you can see that they are the same.)
As this type of string cannot be released, it does not disappear when you expect it to.
If you were to create your string in a way that cannot be optimised, for example:
Then your code will behave as you expect, and your application will (hopefully) crash at your
NSLogline.