views:

48

answers:

3

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 commitAnimations];


}
+1  A: 

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];
 } 
zpasternack
-1 you can't do that. You would be violating the memory management rules since you did not obtain menuBar.view by new, alloc or copy and you have not retained it.
JeremyP
It still gets retained by addSubview. It is probably an autoreleased object, so it will stick around until it is retained by addSubview.You are implying that you can never retain objects not obtained through init or new methods, which is false.
Jergason
A: 

Show us what happens in MenuBarViewController's dealloc method. I suspect you are forgetting to release its instance variables.

JeremyP
A: 

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.

isaac