【发布时间】:2018-01-06 03:50:10
【问题描述】:
在了解了Swift's capture list 以及如何使用它来避免保留循环之后,我不禁注意到OperationQueue 的一些令人费解的地方:它不需要[weak self] 或[unowned self] 来防止内存泄漏.
class SomeManager {
let queue = OperationQueue()
let cache: NSCache = { () -> NSCache<AnyObject, AnyObject> in
let cache = NSCache<AnyObject, AnyObject>()
cache.name = "huaTham.TestOperationQueueRetainCycle.someManager.cache"
cache.countLimit = 16
return cache
}()
func addTask(a: Int) {
queue.addOperation { // "[unowned self] in" not needed?
self.cache.setObject(a as AnyObject, forKey: a as AnyObject)
print("hello \(a)")
}
}
}
class ViewController: UIViewController {
var someM: SomeManager? = SomeManager()
override func viewDidLoad() {
super.viewDidLoad()
someM?.addTask(a: 1)
someM?.addTask(a: 2)
}
// This connects to a button.
@IBAction func invalidate() {
someM = nil // Perfectly fine here. No leak.
}
}
我不明白为什么添加操作不会导致保留周期:SomeManager 强烈拥有 queue,而 queue 又强烈拥有添加的闭包。每个添加的闭包都强烈引用回SomeManager。从理论上讲,这应该会创建一个导致内存泄漏的保留周期。然而 Instruments 表明一切都很好。
为什么会这样?在其他一些多线程、基于块的 API 中,例如 DispatchSource,您似乎需要捕获列表。参见Apple's sample codeShapeEdit,例如ThumbnailCache.swift:
fileprivate var flushSource: DispatchSource
...
flushSource.setEventHandler { [weak self] in // Here
guard let strongSelf = self else { return }
strongSelf.delegate?.thumbnailCache(strongSelf, didLoadThumbnailsForURLs: strongSelf.URLsNeedingReload)
strongSelf.URLsNeedingReload.removeAll()
}
但在同一个代码文件中,OperationQueue 不需要捕获列表,尽管具有相同的语义:你交出一个引用 self 的闭包以异步执行:
fileprivate let workerQueue: OperationQueue { ... }
...
self.workerQueue.addOperation {
if let thumbnail = self.loadThumbnailFromDiskForURL(URL) {
...
self.cache.setObject(scaledThumbnail!, forKey: documentIdentifier as AnyObject)
}
}
我已经阅读了上面的 Swift's capture list 以及相关的 SO 答案,例如 this 和 this 和 this,但我仍然不知道为什么不需要 [weak self] 或 [unowned self] OperationQueue API,而它们在 Dispatch API 中。我也不确定在OperationQueue 案例中如何没有发现泄漏。
任何澄清将不胜感激。
编辑
除了下面接受的答案,我还发现the comment by QuinceyMorris in Apple forums 很有帮助。
【问题讨论】:
标签: swift memory-leaks automatic-ref-counting nsoperationqueue retain-cycle