Need clarification for NSAutoreleasePool

梦想的初衷 提交于 2019-12-07 16:52:06

问题


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.


回答1:


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 from main.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"



来源:https://stackoverflow.com/questions/7286685/need-clarification-for-nsautoreleasepool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!