Most of the differences in these instances is how the memory is managed. If you want a clearer view of what's happening in the background, you might want to peruse the Objective-C Memory Management Guide.
// Version_01
userName = @"Teddy";
This is a String constant that does not have any memory management associated with it. The memory used to hold the value is part of the memory in which the code resides in (essentially). retain
and release
calls on the variable will be ignored.
// Version_02
userName = [NSString stringWithString:@"Gary"];
This is an autoreleased instance of an NSString object. Its retain count is currently one and will be released by the autorelease pool soon unless it is retained.
// Version_03
userName = [[NSString alloc] initWithString:@"Caroline"];
[userName release];
This is a managed instance of an NSString. When it is first initialized, its retain count is one. After releasing it, the retain count went down to zero, therefore, its memory will be deallocated. Referring to the variable userName
after releasing it will cause an EXE_BAD_ACCESS
error.