iOS, Autorelease Pool

iOS Autorelease Pool memory management explained

✍️ Note

Some codes and contents are sourced from Apple’s official documentation. This post is for personal notes where I summarize the original contents to grasp the key concepts

What is Autorelease Pool?

An object that supports Cocoa’s reference-counted memory management system.

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. 

@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.

https://developer.apple.com/documentation/foundation/nsautoreleasepool

screenshot 2024 04 03 at 11.54.58e280afam

AutoRelease Pool

You can send multiple autorelease message to an object. When autorelease pool released, object will receive multiple release message.

screenshot 2024 04 03 at 12.21.10e280afpm
screenshot 2024 04 03 at 12.34.59e280afpm

Common Scenario when Is it useful for? -> Created an object in a Loop!

for (i=0; i < MANY_TIMES; i++)
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

//Create an object and send autorelease message

MyObject *object = [[MyObject alloc] init];
[object autorelease];

//Release all objects that created in this loop.
[pool release];

}

Comments

Leave a Reply

Discover more from Shawn

Subscribe now to keep reading and get access to the full archive.

Continue reading