【发布时间】:2020-02-05 17:56:30
【问题描述】:
我看到了来自 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()
}
}
}
}
【问题讨论】:
-
如果你不使用弱自我,什么都不会发生。这只是一个好习惯。
标签: swift memory-management singleton grand-central-dispatch weak-references