DevPrep

All topics › Memory management

When do you need an autoreleasepool in Swift?

Middle PRO

Essence

Pure Swift objects never go through an autorelease pool — ARC releases them right away. The pool is needed when a loop calls Objective-C APIs that return autoreleased objects: UIImage(data:), Data(contentsOf:), NSString, NSAttributedString, JSONSerialization, Core Graphics/ImageIO wrappers, Core Data (NSManagedObject).

Without your own pool such temporaries live until the nearest pool drains: on the main thread — until the end of the run loop iteration, on a GCD queue — until the end of the current work item. In a loop of thousands of iterations peak memory climbs into the hundreds of megabytes and the app gets jetsammed, even though nothing "leaks".

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store