Matrix
Matrix

Reputation: 7623

What happen when we are writing [Obj autorelease] in Autorelease pool?

What happen when we are writing [Obj autorelease] ?

For example:

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];<br>
 NSMutableString *str = [[[NSMutableString alloc]initWithString:@""] autorelease];<br>
 NSLog(str);<br>
 [str appendString:@" I"];<br>
 NSLog(str);<br>
 [str appendString:@" like"];<br>
 NSLog(str);<br>
 [str appendString:@" programming"];<br>
 NSLog(str);<br>
 [pool drain];<br>
 NSLog(@"%@",str); //invalid

I am confused because i read that "You can add an object to the current autorelease pool for later release by sending it an autorelease message", so when i write

 NSMutableString *str = [[[NSMutableString alloc]initWithString:@"my"] autorelease];

1) After executing above statement, Is str now added to autorelease pool?

2) If str is added to autorelease pool, then if we refer str after that (before releasing/draining pool), like...

 [str appendString:@" I"];
 NSLog(str);
 [str appendString:@" like"];
 NSLog(str);
 [str appendString:@" programming"];
 NSLog(str);

then reference of str will be available from autorelease pool(because str is now added to autorelease pool) or from initial memory location of str....??

Confusing...!! Can any one give me clear idea about this!

Upvotes: 1

Views: 306

Answers (1)

jlehr
jlehr

Reputation: 15617

1) Yes, whenever you send an object an -autorelease message, it is added to the autorelease pool.

2) After executing the following line of code...

NSMutableString *str = [[[NSMutableString alloc]initWithString:@"my"] autorelease];

(which, by the way, could be rewritten like this):

NSMutableString *str = [NSMutableString string]; 

...there are two references to the new string; one in the autorelease pool, and the second in your local variable str. In other words, each contains the address of your string object. So the object isn't really 'in' the pool, anymore than it's 'in' the variable.

When you send a -release message to the pool, it sends -release messages to the objects it currently references. Note that a single object can be sent multiple -autorelease messages in a given cycle, in which case the pool would send a corresponding number of -release messages to the object.

If you're finding this stuff confusing, a great way to get more insight is to read Apple's Memory Management Guide.

Upvotes: 2

Related Questions