6
votes

I study manual memory management and I wonder when autorelease pools drain.

There is 3 situations, that I found: 1 - in the main.m, start from application running and drains on end, therefore releasing all of objects in memory. 2 - when you explicitly create an autorelease pool manually and drain it

Third case is what I'm asking for, and its kind of confusing for me.

As I studied, autorelease objects just like automatic variables in C, that exist only in a logical scope (in function body). Therefore, I suppose that after each function there is a hidden [pool drain];

But, it was pointed out to me that it's not correct as I thought. Apple says, that it drains after an "event". That event might occur when user hit button, table view is reloaded for example.

But that information is not enough to see the whole picture. Could you please clarify for me, when exactly a pool drains for objects, like NSArray *arr = [NSArray array];?

2
The autorelease pool is not drained at the end of every function, but rather every time you yield control back to the run loop. - Rob
@Rob that what I'm asking for, when does that happen? - Evgeniy Kleban
@rob okay, thats pretty nice, but how could i determine which method exactly does pool drain? Is there a list of methods? Or some criteria? - Evgeniy Kleban
@Rob but there is a lot of methods that call "under the hood", like NSObject +load. Obviously, pool doesn't drain anytime NSObject load. I like your explanation but still can't see whole picture :) - Evgeniy Kleban

2 Answers

9
votes

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.

3
votes

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