Search code examples
objective-ccocoamemory-managementautoreleasealloc

Is it incorrect to re-assign to a pointer which contains an autoreleased object?


What is the result of the following?

NSString *myStr = [[[NSString alloc] initWithString:@"Hello World."] autorelease];
myStr = [NSString stringWithString:@"Hello Again."];

Does myStr get correctly released or does this crash, since we would call autorelease on myStr which is now set to a string that is already autoreleased?


Solution

  • Your code example works the way you would expect. autorelease can't somehow change what object it refers to after you send the message. The @"Hello World." and @"Hello Again." objects are different objects, even though your example uses the same pointer variable to refer to them.