今天我做了一些测试,我对结果很好奇。我做了一个有UINavigationController和两个UIViewControllers的应用程序(圆弧)。在第一个视图中有一个按钮,当按下该按钮时,加载第二个视图。在第二个视图中,当检测到摇动手势时,加载第一个视图,依此类推。我在工具中注意到,每次加载视图时,堆都会增长。下面是一些代码
AppDelegate.m
self.navigationController = [[UINavigationController alloc]init];
self.window setRootViewController:self.navigationController];
FirstViewController *firstview = [FirstViewController alloc]init];
[self.navigationController pushViewController:FirstViewController animated:YES]; FirstViewController.m
-(IBAction)loadSecondView
{
SecondViewController *secondview = [SecondViewController alloc]init];
[self.navigationController pushViewController:secondview animated:YES];
}SecondViewController.m
-(IBAction)loadFirstView
{
FirstViewController *firstview = [FirstViewController alloc]init];
[self.navigationController pushViewController:first view animated:YES];
}我不明白为什么会这样。在这种情况下如何避免堆的增长?
发布于 2012-02-10 16:53:12
实际上,每次创建新的视图控制器对象时..这是不应该做的。
所以每次你分配一个新的对象并推入那个视图,它就会被添加到导航堆栈中,因此,内存就会增长。
相反,当您在第一个视图中点击按钮时,您可以弹出当前视图控制器,并通知AppDelegate类显示第二个视图。
类似地,在第二个视图中,当您想要显示第一个视图时,弹出当前视图并通知AppDelegate类推送第一个视图控制器。
发布于 2012-02-10 16:52:46
SecondViewController *secondview = [[[SecondViewController alloc]init] autorelease];
FirstViewController *firstview = [[[FirstViewController alloc]init] autorelease];您应该自动释放视图控制器(对于非ARC)
如果第二个控制器先打开,则应执行popViewController。如果你不返回,堆将会增长
https://stackoverflow.com/questions/9225004
复制相似问题