Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of @autoreleasepool in Swift?

In Swift, I notice there is no @autoreleasepool{} construct, although Swift does use ARC. What is the proper way to manage an autoreleasepool in Swift, or has it been removed for some reason?

like image 884
Skotch Avatar asked Jun 10 '14 22:06

Skotch


People also ask

What is @autoreleasepool in IOS?

Overview. An autorelease pool stores objects that are sent a release message when the pool itself is drained. Important. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

What is auto release pool in Swift?

The autoreleasepool allows you to explicitly manage when autorelease objects are deallocated in Swift, just like you were able to in Objective-C. Note: When dealing with Swift native objects, you generally will not receive autorelease objects.

What is pool in Objective-C?

A pool is created at the first brace and is automatically drained at the end of the scope. Any object autoreleased within the scope is sent the release message at the end of the scope. Let's take a look at this example: for (int i = 0; i < 100000; i++) { [self doMagicWith:i];

How an Autorelease pool works at the runtime level?

To use an autorelease pool, send an object an -autorelease message instead of a -release message. The receiver is not immediately released; it is simply added to the autorelease pool. Later—usually long after your code has finished—the pool is drained and each object in the pool receives its -release message.


2 Answers

The syntax is as follows:

autoreleasepool {   /* code */  } 

Unfortunately Apple's WWDC 2014 videos no-longer seem to be available. Incase it comes back, it was covered in WWDC 2014 session video number 418 "Improving Your App with Instruments".

The swift documentation doesn't contain anything useful currently. But you can find plenty of good information under the Obj-C Runtime Reference for NSAutoreleasePool and the Advanced Memory Management Programming Guide.

Note: Auto Release Pools are no-longer as relevant today as they were in the past. Modern code should use Automatic Reference Counting which does not use release pools at all. However there's still a lot of legacy code, including in Apple's frameworks, that use auto release pools as of 2021. If you're doing any kind of batch process on images as one example, you probably should be using an autoreleasepool block.

like image 121
Abhi Beckert Avatar answered Nov 21 '22 17:11

Abhi Beckert


Just FYI, Xcode constructed the full code as follows:

autoreleasepool({ () -> () in     // code               }) 

Guess the parentheses identifies the functions closure.

like image 43
Saukwood Avatar answered Nov 21 '22 19:11

Saukwood