I’m struggling a bit with figuring out how to properly set up my view controllers to gracefully handle memory warnings.
At the moment, I’m getting an EXC_BAD_ACCESS crash from a view further back in the navigation controller stack whenever the app receives a memory warning.
The bad access occurs with my table view. Here’s how I’m instantiating it:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UITableView *table = [[[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.size.width, self.view.bounds.size.height - self.navigationController.navigationBar.bounds.size.height) style:UITableViewStyleGrouped] autorelease];
table.dataSource = self;
table.delegate = self;
self.tableView = table;
[self.view addSubview:table];
[table release];
...other stuff...
}
And here’s my viewDidUnload:
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.tableView = nil;
}
Upon a memory warning, viewDidUnload is called, as expected, but I get an EXC_BAD_ACCESS crash on the self.tableView = nil line.
Am I setting up my tableView in the wrong place? I’m not using a nib file, so should I be building it elsewhere? Am I somehow passing it off to the view controller incorrectly? etc etc
Any help would be much appreciated. I still haven’t grokked the sequence of events that occurs upon a memory warning, and Level 1 Memory Warnings seem to be obnoxiously common.
You’re calling
releasetwice ontable; once with a deferred release withautoreleasewhen you’re creating it, and again with[table release];after you’ve added it as a subview ofself.view. Remember, if the property fortableViewis ‘retain’, then it will be retained on assignment (when assigned with dot syntax) — and, that addSubview will retaintableas well when you add it. So, you just need to leave theautoreleasein there — since that deferred release (which will be balanced out by the retain that happens when you sayself.tableView = table;.