What is the equivalent of @autoreleasepool in Swift?
Automatic Ref-CountingSwiftNsautoreleasepoolAutomatic Ref-Counting Problem Overview
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?
Automatic Ref-Counting Solutions
Solution 1 - Automatic Ref-Counting
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.
Solution 2 - Automatic Ref-Counting
Just FYI, Xcode constructed the full code as follows:
autoreleasepool({ () -> () in
// code
})
Guess the parentheses identifies the functions closure.
Solution 3 - Automatic Ref-Counting
There is! It's just not really mentioned anywhere.
autoreleasepool {
Do things....
}
Solution 4 - Automatic Ref-Counting
I used this kind of structure in my code. This function is create thumbnail image from Video URL.
func getThumbnailImage(forUrl url: URL) -> UIImage? {
return autoreleasepool{ () -> UIImage in
let asset: AVAsset = AVAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
var thumbnailImage: CGImage?
do {
thumbnailImage = try imageGenerator.copyCGImage(at: CMTimeMake(value: 1, timescale: 60) , actualTime: nil)
return UIImage(cgImage: thumbnailImage!)
} catch let error {
print(error)
}
return UIImage(cgImage: thumbnailImage!)
}
}