堆内存正在增长

时间:2012-02-10 08:44:21

标签: objective-c ios memory-management instruments

今天我做了一些测试,我很好奇结果。我制作了一个应用程序(ARC),它有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];
}

我无法弄清楚为什么会这样。在这种情况下如何避免增长堆?

2 个答案:

答案 0 :(得分:1)

实际上,每次创建新的视图控制器对象时都应该这样做。

因此,每次分配新对象并推送该视图时,它都会被添加到导航堆栈中,因此内存会增长。

相反,当您处于第一个视图并点击按钮时,您可以弹出当前视图控制器并通知AppDelegate类显示第二个视图。

同样在第二个视图中,当您想要显示第一个视图时,弹出当前视图并通知AppDelegate类推送第一个视图控制器。

答案 1 :(得分:0)

SecondViewController *secondview = [[[SecondViewController alloc]init] autorelease];

FirstViewController *firstview = [[[FirstViewController alloc]init] autorelease];

你应该自动释放viewcontrollers(不是ARC)

如果第二个控制器先打开,你应该做popViewController。如果你不回来,堆会增长