我从raywenderlich那里找到了一个教程,作者为处理单例中的线程问题提供了一些很好的技巧。但是,当使用单例类中的闭包时,他使用的是“弱”引用循环。真的需要吗,因为类是单例,所以应该始终有一个实例?
final class PhotoManager {
private init() {}
static let shared = PhotoManager()
private var unsafePhotos: [Photo] = []
let concurrentPhotoQueue = DispatchQueue(label: "com.jeesson.googlypuff.photoQueue", attributes: .concurrent)
var photos: [Photo] {
var photoCopy:[Photo]!
concurrentPhotoQueue.sync {
photoCopy = self.unsafePhotos
}
return photoCopy
}
func addPhoto(_ photo: Photo) {
// Do we need 'weak self here.. and why?
concurrentPhotoQueue.async(flags: .barrier) {[weak self] in
// 1
guard let self = self else {
return
}
self.unsafePhotos.append(photo)
DispatchQueue.main.async { [weak self] in
//self?.postContentAddedNotification()
}
}
}
}
在DispatchQueue
关闭的情况下,根本不添加任何捕获列表。
DispatchQueue
闭包不会引起保留周期,因为self
它不拥有它们。
基本上不需要单例对象内的捕获列表,因为单例永远不会被释放。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句