views:

59

answers:

3

Here i used auto-release for 'tempString' in the method 'test'. According to the rule, i should use "[temp retain]" in the main . But i didnt use it. still it works fine and prints the output. Then what is the need of "retain"? Can anyone pls tell me the reason? Thanks in advance.

-(NSMutableString *) test : (NSMutableString *) aString{

 NSMutableString *tempString=[NSMutableString  stringWithString:aString];

 [tempString appendString:@" World"];

  return tempString;}

int main (){

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

 MemoryMgmt *memoryMgmt=[[MemoryMgmt alloc] init ];
 NSMutableString *str1 =@"Hello";

 NSMutableString *temp = [memoryMgmt test: str1];

 NSLog(@" %@",temp);

 [pool drain];
 return 0;
}
A: 

When you auto-release an object it will release at the end of the run-loop when the pool is drained or released...In your case, since you start a new thread, you manage the autorelease pool, the string temp does not release until you drain your pool, therefore when you use it, it is still valid...hope that helps

Daniel
+3  A: 

stringwithString should return an autoreleased NSMutableString, but that doesn't actually get released until the NSAutoReleasePool drains. You are using the object while the pool is still retaining it and only draining the pool afterwards, releasing the object.

When you receive an autoreleased object from somewhere, you should only retain it if you intent to keep track of the object beyond the current variable scope. If you were to retain the object, but your reference were to go out of scope (as it does after your current function call completes), you would leak the object.

What you are doing here is actually correct, since you don't keep the reference to temp anywhere but in your local scope.

Gerco Dries
A: 

That works because the Autorelease pool doesn't get emptied until the end of the tool's execution. However, it is in fact correct usage: you return an autoreleased object from a method that doesn't claim to be passing ownership to the caller. Some people do

return [[tempString retain] autorelease];
Graham Lee