Leak when adding subview
So Instruments tells me I have three memory leaks originating in this method (specifically, it points out the line: [self.view addSubview:menuBar.view];
I can't see a leak and am racking my brains. I'm keeping a reference to the menuBar object and am releasing it. Anyone smarter than me that can explain? Is it a coincidence that I have three menubar items in my XIB and I'm getting three leaks?
Here is the entire method:
// root vc calls to toggle display state of menu bar on screen
-(IBAction) showToolBar {
//if no toolbar exists, create one and add it to the view
if (!menuBarView) {
MenuBarViewController *menuBar = [[MenuBarViewController alloc] initWithNibName:@"MenuBarViewController" bundle:nil];
menuBar.book = self.selectedTitleDeck;
menuBar.booksArray = self.allTitleDeck;
self.menuBarView = menuBar;
[self.view addSubview:menuBar.view];
[menuBar release];
}
CGRect frame = menuBarView.view.frame;
[UIView beginAnimations:nil context:NULL];
if (self.toolBarIsDisplayed == NO) {
//show the toolbar
frame.origin.y = 725;
self.toolBarIsDisplayed = YES;
} else if (self.toolBarIsDisplayed == YES) {
//hide the toolbar
frame.origin.y = 788;
self.toolBarIsDisplayed = NO;
}
self.menuBarView.view.frame = frame;
[UIView commitAnimation开发者_StackOverflow中文版s];
}
addSubview: retains the view passed into it (see the reference). Once you call addSubView, you can release that view, like:
MenuBarViewController *menuBar = [[MenuBarViewController alloc] initWithNibName:@"MenuBarViewController" bundle:nil];
menuBar.book = self.selectedTitleDeck;
menuBar.booksArray = self.allTitleDeck;
self.menuBarView = menuBar;
[self.view addSubview:menuBar.view];
[menuBar.view release];
[menuBar release];
}
Show us what happens in MenuBarViewController's dealloc method. I suspect you are forgetting to release its instance variables.
As suggested in the comments to my question, the problem was not in the code but in running my app in the simulator and trying to detect memory leaks.
When Instruments is run against the code on the device, no leaks are reported.
My consolation prize is a far more profound understanding of memory management unearthed in two days of trying to locate a leak that didn't exist.
Thanks to all for your advice, much appreciated.
精彩评论