Search code examples
automatic-ref-countingswiftnsautoreleasepool

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?


Solution

  • 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.