What reasons are there for doing in three lines what could be done in one?
Here is some code from developer.apple.com:
UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.navigationController = aNavigationController;
[aNavigationController release];
…and the same thing in one line:
self.navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
It seems clean, simple, and straightforward enough. I’ve had trouble in the past with a property not being retained, causing [object release] to destroy the object when it wasn’t supposed to (so far as I could tell – the retain attribute was set). Using the one-line formula works like a dandy.
The Objective-C memory management rules dictate that by
allocing an object instance you are a (shared once other objectsretainit) owner of that instance and so you mustreleasetheUINavigationControllerwhen you want to relinquish ownership to prevent a memory leak. In a non-garbage collected environment (e.g. on the iPhone) this means balancingallocorcopy(or methods that contain “alloc” or “copy”) withreleaseorautorelease. Your second snippet would then beIf you can avoid using
autoreleaseon a memory-limited environment (like the iPhone), it’s better to use explicitrelease.-[NSObject autorelease]adds the receiver to the currentNSAutoreleasePoolwhich will subsequently call-releaseon the objects in the pool ‘some time in the future.’ When you want to be careful about memory usage, ‘some time in the future’ is not a good idea. Thus, on the iPhone your first example is the standard usage.