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];
?
An autorelease pool stores objects that are sent a release message when the pool itself is drained. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.
An autorelease pool is actually a collection of objects that will be released at some point in the future (either at the end of the thread's run loop or at the end of the scope of an autorelease pool). When a pool is drained, all the objects in the pool at that time are sent the release message.
Memory management in swift is handled with ARC (= automatic reference counting). This means that active references to objects are counted and objects are released when they aren't referenced anymore.
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:
autorelease
is sent to an object, it is added to the autorelease pool at the top of the stack.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With