I have a rather unusual situation, and I’m not quite understanding the memory management properly.
I have a UITableViewController for displaying messages that then creates a UINavigationController and adds its view as a subview of the current view in order to display it. The issue I’m having is that Xcode reports I have a potential memory leak (and I agree) due to not releasing the UINavigationController, but when I release it as in the code below, the app crashes when I click back to return to the Table View.
I used a retained property in the UITableViewController to keep track of the current UINavigationController and manage the retain counts, but clearly I’m missing something here.
Note: The crash occurs when the Back button is clicked with message -[UILayoutContainerView removeFromSuperview:]: unrecognized selector sent to instance 0x5537db0
Also note that if I remove the [nc release] line of code, it works just fine.
Here’s my code:
@property(nonatomic, retain) UINavigationController *currentNavigationController;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UINavigationController *nc = [[UINavigationController alloc] init];
CGRect ncFrame = CGRectMake(0.0, 0.0, [[self view] frame].size.width, [[self view] frame].size.height);
[[nc view] setFrame:ncFrame];
// I created a CurrentNavigationController property to
// manage the retain counts for me
[self setCurrentNavigationController:nc];
[[self view] addSubview:[nc view]];
[nc pushViewController:messageDetailViewController animated:YES];
UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemRewind target:[nc view] action:@selector(removeFromSuperview:)];
nc.navigationBar.topItem.leftBarButtonItem = bbi;
[bbi release];
[nc release];
}
UINavigationController “nc” that you created is only usable inside this method. It is not stored anywhere after this method (because you release it). So you add navigationController’s view to your class view as subview, and then you delete navigationController. That’s wrong. When views and viewControllers try to refer to their navigationController(when it does not exist), your app will crash.
Here is code for didSelectRowForIndexPath method:
Selector for removeFromSuperview method shouldn’t have “:” in the end. It has no arguments 🙂