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?
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.
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.
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];
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.
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.
Just FYI, Xcode constructed the full code as follows:
autoreleasepool({ () -> () in // code })
Guess the parentheses identifies the functions closure.
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