Proper NSArray initialization for ivar data in a method
- by Joost Schuur
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. I'm guessing 'self.breadTypes = ...' copies the data to the new array, which is why the original array can be safely released, correct?