开发者

ViewController doesn't get released

开发者 https://www.devze.com 2023-02-02 09:33 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消