Voloda2
Voloda2

Reputation: 12597

Why is autorelease object still alive?

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);  
}

Upvotes: 1

Views: 120

Answers (2)

一二三
一二三

Reputation: 21239

Strings (NSString instances and statically allocated strings with @"") are immutable in Cocoa, so when you try to create a new NSString from a statically allocated one, the NSString class can make an optimisation: a new NSString instance is not created (the object created when you called -alloc is immediately released), and the reference to your statically allocated string is returned. That is, the line:

NSString *localString = [[[NSString alloc] initWithString:@"I don't know."] autorelease];

Is actually equivalent to:

NSString *localString = @"I don't know.";

(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:

NSString *localString = [[[NSString alloc] initWithFormat:@"%@", @"I don't know."] autorelease];

Then your code will behave as you expect, and your application will (hopefully) crash at your NSLog line.

Upvotes: 4

Ilanchezhian
Ilanchezhian

Reputation: 17478

If you have tried any classes (any custom classes) other than NSString , then it would not be alive..

Upvotes: 0

Related Questions