Every time I turn the page in my app, I am removing and releasing the previous viewController - but for some reason it is still in memory. I know this, because开发者_开发问答 after using the app for a while, I get 47 memory warnings - one from each view controller - if I had opened 47 pages before the memory warning occurred. I get 60 memory warnings if I had opened 60 pages before the memory warning occurred. And so on...
This is the code that runs from page to page:
UIViewController *nextController;
Class nextClass = [pageClasses objectAtIndex:(currentPageIndex - 1)];
nextController = [[nextClass alloc] initWithNibName:[pageNibs objectAtIndex:(currentPageIndex - 1)] bundle:nil];
[nextController performSelector:@selector(setDelegate:) withObject:self];
[currentPageController.view removeFromSuperview];
[self.view addSubview:nextController.view];
[currentPageController release];
currentPageController = nextController;
[currentPageController retain];
[nextController release];
Can anybody point to any issues they see?
Thanks so much!
As as aside, make sure you also nil
any outlets your viewController has in viewDidUnload
and generally do the opposite of any corresponding code in viewDidLoad
. I see a lot of iOS code which doesn't do this and it stops the runtime properly unloading view controllers and associated views.
Have you played with the Behavior and Memory sections of the Window Attributes panel in IB's Inspector? This is where you usually control memory use and release stuff (outside of the code itself). Try changing values for the view object in question, as well as on the window (or whatever it is for iPhone).
I believe it's because you're calling retain
on currentPageController
. I just recently asked a similar question and got a ton of clarification on memory management.
EDIT: What if you did something like:
[currentPageController.view removeFromSuperview];
[currentPageController release];
Class nextClass = [pageClasses objectAtIndex:(currentPageIndex - 1)];
currentPageController = [[nextClass alloc] initWithNibName:[pageNibs objectAtIndex:(currentPageIndex - 1)] bundle:nil];
[currentPageController performSelector:@selector(setDelegate:) withObject:self];
[self.view addSubview:currentPageController.view];
It cleans up the code a bit and won't leak memory.
精彩评论