我的应用程序一开始是基于 View 的,但后来我不得不改为基于导航。我这样做的方法是在我的 AppDelegate
中创建一个 UINavigationController 成员,并在 didFinishLaunchingWithOptions
方法中调用 pushViewController
:
@property (nonatomic, retain) IBOutlet UINavigationController *navigator;
// didFinishLaunchingWithOptions implementation
MainController *mainView = [[MainController alloc] initWithNibName:@"MainController" bundle:nil];
navigator = [[UINavigationController alloc]init];
[navigator pushViewController:newSongView animated:YES];
[mainView release];
在我的 MainController View
中,我有一个调用此方法并将用户发送到下一个 View 的按钮:
- (IBAction)newViewLoader:(id)sender {
SecondViewController *secVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self.navigationController pushViewController:secVC animated:YES];
}
这工作正常,但按下此按钮的那一刻,模拟器开始使用 5MB 以上的内存。当我按下导航栏上的 back
按钮,而不是按下调用 newViewLoader
方法的按钮时,模拟器多占用了 5MB。以此类推,每次加载第二个 View 时。所以加载这个 View 是相当昂贵的。
有没有什么方法可以在按下后退按钮时卸载 View ,这样内存就不会在每次打开 View 时都增加?这里是 screenshot每次加载 View 时都会发生什么。
最佳答案
如果您不使用 ARC,那么您的 IBAction 中至少有一个内存泄漏。应该是:
- (IBAction)newViewLoader:(id)sender {
SecondViewController *secVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self.navigationController pushViewController:secVC animated:YES];
[secVC release];
}
或者我喜欢的:
- (IBAction)newViewLoader:(id)sender {
SecondViewController *secVC = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];
[self.navigationController pushViewController:secVC animated:YES];
}
否则你的 secVC 永远不会被释放。您可以尝试添加版本,看看会发生什么。
但是你真的应该使用 ARC,它是自动引用计数。这会为您处理发布。在这里阅读:http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html
关于objective-c - 使用 UINavigationController View 进行内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219738/