在 Swift 中,@autorelease 的等价物是什么?

在 Swift 中,我注意到没有 @autoreleasepool{}构造,尽管 Swift 使用 ARC。在 Swift 中管理自动发布池的正确方法是什么,或者由于某种原因已经删除了它?

17523 次浏览

There is! It's just not really mentioned anywhere.

autoreleasepool {
Do things....
}

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.

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!)
}
}