This morning I ran into a crash in an iPhone app I am working on and while I fixed the bug, I’m curious about syntactic reason it was a problem.
Here is my code reduced to simple elements. I am populating items in a TableView using an NSArray for the items. The NSArray is a property:
@interface FooViewController : UITableViewController {
NSArray *stuff;
}
@property (nonatomic, retain) NSArray *stuff;
And in my implementation file:
@synthesize stuff;
- (void)viewDidLoad {
NSArray *arr = [[NSArray alloc] initWithObjects:@"", @"Item 1", @"Item 2",
@"Lorem", @"Ipsum", nil];
self.stuff = arr;
[arr release];
}
Now, when I first wrote the method, I accidentally left off the “self.” and that caused the bomb. Although while testing, it worked at first blush. I’d tried:
stuff = arr;
NSLog(@"%d", [stuff count]);
But using stuff in other methods bombed. Now that I’ve fixed the problem, I can use [stuff count] in other places.
So why can I use stuff in some places but in others I must use self.stuff?
This would have also worked properly:
Because the array was retained by alloc. But it’s usually better to stick to the dot notation if you have a property and use the autorelease array creation methods, where you get retains “for free” from the property:
You probably just left it out to keep things simple, but you also need to free this array in dealloc: