objective-c - 堆内存不断增长

标签 objective-c ios memory-management instruments

今天我做了一些测试,我很好奇结果。我制作了一个应用程序(ARC),其中有 UINavigationController 和两个 UIViewController。在第一个 View 中有一个按钮,按下该按钮时会加载第二个 View 。在第二个 View 中,当检测到摇动手势时,将加载第一个 View ,依此类推。我在仪器中注意到的是,每次加载 View 时堆都会增长。这是一些代码

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];
}

我不明白为什么会发生这种情况。在这种情况下如何避免堆增长?

最佳答案

实际上,每次创建新的 View Controller 对象时......都不应该这样做。

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

相反,当您在第一个 View 中并点击按钮时,您可以弹出当前 View Controller 并通知 AppDelegate 类显示第二个 View 。

类似地,在第二个 View 中,当您想显示第一个 View 时,弹出当前 View 并通知 AppDelegate 类推送第一个 View Controller 。

关于objective-c - 堆内存不断增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225004/

相关文章:

objective-c - 是否可以在 Objective-C 中动态实现协议(protocol)?

ios - 为可调整大小的 UIView 设置最小和最大宽度和高度

iphone - 核心数据 - 在 vi​​ewDidLoad 之前调用数据源方法

objective-c - 在 Objective-C 中保留 block 中的可变变量而不引起循环引用

android - Volley - 直接下载到文件(没有内存字节数组)

iphone - 无法准确设置表格单元格背景和文本颜色。

ios - 圆角 UITableViewCell (iOS)

ios - presentingViewController 总是得到 UITabBarController

iOS - 如何删除以前添加的 UIView 子层

.net - 内存中的 System.Collections.Generic.List<T> 大小