需要澄清 NSAutoreleasePool
每当我们调用 autorelease
方法时,它的对象都会转到 NSAutoreleasePool
。当池耗尽时,它会向池中的所有对象发送释放消息。
我的问题是;
在主函数中有一个NSAutoreleasePool
。我想知道;当我们调用 autorelease 方法时,它会将对象发送到哪里?我是说;它将对象发送到位于主函数(或)某处的NSAutoreleasePool
?
提前致谢。
Whenever we are calling autorelease
method, its object is going to NSAutoreleasePool
. When the pool is drained, it is sending release to all the objects in the pool.
My question is;
In the main function there is one NSAutoreleasePool
. I want to know that; when we call the autorelease
method, where it is sending the object ? I mean; it is sending the object to NSAutoreleasePool
which is in main function (or) somewhere ?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上有一堆自动释放池。每当您执行
[[NSAutoreleasePool alloc] init]
时,新创建的池都会自动放置在自动释放池堆栈的顶部。您可以在需要时创建自己的池。更准确地说:每个线程上都有一个自动释放池堆栈。因此,每当您创建一个线程(例如使用
[foo PerformSelectorInBackground:@selector(bar) withObject:baz]
)时,您需要做的第一件事就是创建一个池,否则您的对象会泄漏(这创建臭名昭著的消息,例如“NSAutoreleaseNoPool(): Object 0xd819d0 of class NSCFString autoreleased with no pool in place - just Leaking”,并且是一个 这里非常常见的问题)。当您调用 autorelease 时,该对象将注册到当前线程的最顶层自动释放池(即:该线程上最后创建的自动释放池)。主运行循环有自己的自动释放池,该池在每次运行循环迭代时都会被清空(AFAIK)。 main.m 中的池用于捕获任何对象,例如 Cocoa Touch 在创建运行循环自动释放池之前可能在内部生成的对象。
编辑:有关更多幕后信息,请参阅Mike Ash 的“让我们构建 NSAutoreleasePool”
There is actually a stack of autorelease pools. Whenever you do
[[NSAutoreleasePool alloc] init]
that newly created pool is automatically put on top of the autorelease pool stack. You can create your own pools whenever you need it.To be more precise: there is a stack of autorelease pools on each thread. So whenever you create a thread (for example with
[foo performSelectorInBackground:@selector(bar) withObject:baz]
) the very first thing you need to do is create a pool or else your objects leak (this creates the infamous messages like "NSAutoreleaseNoPool(): Object 0xd819d0 of class NSCFString autoreleased with no pool in place - just leaking" and is a very frequently asked question here on SO).When you call
autorelease
, the object is registered with the top-most autorelease pool of the current thread (that is: the one that was created last on that thread). The main run loop has its own autorelease pool that is emptied on each run loop iteration (AFAIK). The pool frommain.m
is there to catch any objects that for example might be generated internally by Cocoa Touch before it gets to create the run loop autorelease pool.Edit: For more behind-the-scenes information, see Mike Ash's "Let's Build NSAutoreleasePool"