Autorelease pools in Objective-C - release main AutoreleasePool?

我的未来我决定 提交于 2019-12-03 15:01:03

1) Do all autoreleased objects stay in that pool until the termination of the app?

Autoreleased objects by definition are owned by their autorelease pool until that pool is drained. When you send -autorelease to an object, that object is added to a list of objects that the pool will release later. Autorelease pools are organized in a stack, with the pool at the top of the stack being the pool to which any objects sent -autorelease are added. The pool created in main() is generally not the one at the top of the stack. For example, the run loop will create an autorelease pool at the beginning of each iteration.

2) If 1 is true, does creating an autoreleased object without a local autorelease pool (therefore placing that object in the main.m pool) keep that object in memory until termination of the app or a memory warning is received?

It would if the pool created in main() were the topmost pool, but as described above, that usually won't be the case.

3) When is the main.m autorelease pool drained, other than when the app receives a memory warning or the application is terminated?

There's no difference between the pool created in main() and any other autorelease pool. They're all drained when the pool is released, or at the end of the block if you used the @autorelease directive.

cbranch

From the documentation:

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. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

So, autoreleased objects in the default pool will only survive the duration of the current event.

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