When do autorelease pools drain?

The documentation is not specific on when the "main" autorelease pool drains, but generally you can assume it is drained at the end of the application's main event loop.

Here's what happens with regards to autorelease pools:

  1. An autorelease pool is created when an application starts.
  2. When another pool is created, it is added to the top of the autorelease pool stack.
  3. When a autorelease is sent to an object, it is added to the autorelease pool at the top of the stack.
  4. When release is sent to an autorelease pool, it, in turn, sends release to any object in the pool.

#4 typically happens automatically (for the main autorelease pool) at the end of the main event loop.

The documentation for NSAutoreleasePool has more information, including this relevant tidbit:

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.


When I'm using reverse engineering tool to analysis Foundation framework. Then I found autorelease pool created at begin of runloop and release at end of runloop. image: autorelease start at runloop