This is probably a dumb question, but in the introduction to TableViews, the author has a property of NSArray *listData to fill the table with dummy data. In the viewDidLoad, he basically does this:
- (void)viewDidLoad {
NSArray *array = [[NSArray alloc] initWithObjects@"1", @"2", @"3", more stuff, nil];
self.listData = array;
[array release];
...
}
Why does he create another array and set it to the property as opposed to doing something like
- (void)viewDidLoad {
listData = [[[NSArray alloc] initWithObjects@"1", @"2", @"3", more stuff, nil]autorelease];
Is it to manage memory better by using alloc/init vs the autorelease pool? Or is the second way just not going to work? Thanks.
Your code is wrong and is likely to crash. In his code, he calls
alloc, meaning the retain count is 1. He then assigns it to a property. I’m assuming this property is declared to beretain, in which case the retain count would go up to 2. He then calledrelease, which drops the retain count back to 1.In your code, you call
alloc, meaning the retain count is 1, then you callautorelease, which means that the retain count will drop to 0 and the object’s memory will be deallocated soon. You assign the object to an instance variable – not a retained property like he does – so you won’t increase the retain count any more. This means that you’ll be left with a dangling pointer to memory that could be overwritten with anything else at any time. When you try to accesslistData, you’ll crash because it is likely to have been overwritten.Please read Memory Management Programming Guide if you do not understand what is happening here.
Having said that, the core of your question is valid. There’s nothing stopping him from doing the same as you, except assigning to a retained property instead of an instance variable.