Search code examples
iphoneobjective-cmemory-managementretainautorelease

why does it works fine without 'retain' the object?


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

Solution

  • 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.