自动释放池和在iOS下调用释放时 [英] Autorelease pools and when release is called under iOS

查看:313
本文介绍了自动释放池和在iOS下调用释放时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要澄清的东西。

假设我有以下代码:

- (void) viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  for (int i = 0; i < 5000000; i++) {
    NSString *s = [NSString stringWithFormat:@"Hello, %@!", @"World"];
  }
}

这将在此函数调用中创建500万个自动释放字符串。我希望这可以保持这些对象,直到应用程序的终止,因为我看到的唯一的@autoreleasepool是一个包装应用程序实例化在main.m。不是这样的。

This will create 5 million autoreleased strings within this function call. I was expecting this to keep those objects around until the termination of the application, as the only @autoreleasepool I see is the one wrapping the application instantiation in main.m. That's not the case, though. At the end of this function call, it seems they all get their release called and are removed from memory.

这个文档:

https://developer.apple .com / library / mac / documentation / cocoa / reference / foundation / Classes / NSAutoreleasePool_Class / Reference / Reference.html

声明在事件循环的每个循环的开始处的主线程上的自动释放池,并且在结束时排出它,从而释放在处理事件时产生的任何自动释放的对象。

States that "The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event."

这对我有意义,但这是在UIKit下,而不是应用程序工具包。我的问题是,UIKit / Cocoa Touch在这种情况下做同样的事情,还是有我的对象被释放的另一个解释?

That makes sense to me, but this is under UIKit, and not Application Kit. My question is, does UIKit/Cocoa Touch do the same thing in this case, or is there another explanation for my objects getting released?

谢谢! b $ b

推荐答案

是的,UIKit做同样的事情。系统创建的主线程自动释放池在每个运行循环周期结束时耗尽。最好不要依赖这个确切的生命周期在你自己的代码。如果你手动创建一个新的线程(使用例如NSThread),你负责在该线程上创建自动释放池。

Yes, UIKit does the same thing. The system-created, main thread autorelease pool is drained at the end of every run loop cycle. It's probably best not to rely on this exact lifetime in your own code. If you create a new thread manually (using e.g. NSThread), you're responsible for creating the autorelease pool on that thread.

编辑:Rob的回答提供了一些很好的附加信息关于ARC下的行为。一般来说,可以公平地说,由于ARC能够进行一些优化,对象不太可能在自动释放池中结束。

Rob's answer provides some good additional information regarding behavior under ARC. In general, it's fair to say that objects are less likely to end up in the autorelease pool due to some optimizations ARC is able to make.

这篇关于自动释放池和在iOS下调用释放时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆