I’m new to Objective-C and iPhone development and have been using Apress’ Beginning iPhone 3 Programming book as my main guide for a few weeks now. In a few cases as part of a viewDidLoad: method, ivars like a breadTypes NSArray are initialized like below, with an intermediate array defined and then ultimately set to the actual array like this:
NSArray *breadArray = [[NSArray alloc] initWithObjects:@"White", @"Whole Weat", @"Rye", @"Sourdough", @"Seven Grain", nil];
self.breadTypes = breadArray;
[breadArray release];
Why is it done this way, instead of simply like this:
self.breadTypes = [[NSArray alloc] initWithObjects:@"White", @"Whole Weat", @"Rye", @"Sourdough", @"Seven Grain", nil];
Both seem to work when I compile and run it. Is the 2nd method above not doing proper memory management? I assume initWithObjects: returns an array with a retain count of 1 and I eventually release breadTypes again in the dealloc: method, so that wraps things up nicely:
- (void)dealloc {
...
[breadTypes release];
[super dealloc];
}
The setter is defined via a standard property (and eventual synthesize) directive:
@property (nonatomic, retain) NSArray *breadTypes;
The second way indeed may lead to memory leak; you explicitly create an array (taking the ownership), but you are not releasing it.
The best way to mix create and assignation is to use the class constructors (See NSArray reference). When invoking class constructor, you do not take ownership of the object, so there is memory leaks: