When it comes to allocating and initializing objects that are declared @properties of a class I’ve seen two main patterns in various bits of sample code, so given the following (made up) header code —
@interface Class : Superclass {
Object *anObject;
}
@property (nonatomic, retain) Object *anObject;
The first, direct assignment:
self.anObject = [[Object alloc] init];
The second, indirect method creates a temporary object that is then assigned to the property and released:
Object *tempObject = [[Object alloc] init];
self.anObject = tempObject;
[tempObject release];
What’s the benefit to the second method over the first?
The difference between those two blocks of code is that the first one is a memory leak. When you call
[Object alloc]you get “ownership” of the object, and are responsible for-releaseing it sometime. Then when you call[self -setAnObject]it takes a second ownership, setting the retain count for the new instance to 2. If the method doing the creation returns without relinquishing its ownership of the new instance, you end up with a leak.Try this:
self.anObject = [[[Object alloc] init] autorelease];This works because
[NSObject -autorelease]returns self and also schedules a-releasecall “sometime in the future” which usually means at the end of the current run loop.