我看到了一个来自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()
}
}
}
}