iphone - 使用 ARC 进行内存管理,奇怪的行为

标签 iphone ios ipad automatic-ref-counting

我声明了一个全局对象:

YViewController * yViewController

在应用程序启动时我正在调用:

[self methodOne];

该方法执行以下操作:

-(void)methodOne
{
 yViewController = [[YViewController alloc] initWithNibName:@"YViewController" bundle:nil];
 self.window.rootViewController=yViewController;
}

当在 YViewController 中单击按钮时,我正在调用:

[self methodTwo];

该方法执行以下操作:

-(void)methodTwo
{
  XViewController * xViewController = [[XViewController alloc] initWithImage:myImage];
  self.window.rootViewController=xViewController;
}

当点击 XViewController 上的后退按钮时,我正在调用 [self methodOne];,它将导航回 YViewController

问题是,当我使用 ARC 时,我无法刷新/释放 xViewController 对象。另外在检查仪器时, 当我在 XViewControllerYViewController 之间来回点击时,XViewController 的内存不断增加。

在这种情况下如何使用 ARC 管理内存?

最佳答案

如果 XViewController 的源代码是开放的,我会调整它以配合导航。任何方法..

好吧,基本上你每次都会创建一个新的 ViewController 对象,这就是导致内存堆的原因。

您应该将“XViewController * xViewController”和“YViewController * yViewController”作为类变量,并且您的方法应该是这样的,例如。

查看该对象是否存在,如果存在,则不再分配。

-(void)methodTwo
{
 if(xViewController == nil)
 {
   xViewController = [[XViewController alloc] initWithImage:myImage];
 }
  self.window.rootViewController=xViewController;

}

关于iphone - 使用 ARC 进行内存管理,奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11625494/

相关文章:

iphone - iOS : How to make TableView not to fill the height?

ios - 更改 UILabel 的文本使其在使用 UIViewKeyframeAnimations 时重新出现

ios - Apple Watch - 仅在手机上的应用程序处于事件状态时获取数据

iphone - 使用 Quartz 2D 绘制桥梁

ios - 内容更改时 WKWebView 不调整大小

ios - UITabBarControllerDelegate 方法未被调用

带有动画的 iOS 单元测试

iphone - 使用滑动手势查看导航

iphone - 在 UIImageView 上添加不透明度为 0.3 的黑色叠加层

iphone - 将 NSManagedObject 转换为子类对象