是否需要在单例中使用弱引用 class?
Is it required to to use weak reference's within a singleton class?
我看到了 raywenderlich 的教程,作者提供了一些关于处理单例线程问题的好技巧。但是当在单例 class 中使用闭包时,他使用的是 'weak' 引用循环。真的有必要吗,既然 class 是一个单例,它应该总是有一个实例吗?
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
不拥有它们。
基本上不需要单例对象内的捕获列表,因为单例永远不会被释放。
一些单例的生命周期与应用程序生命周期相关联。某些单例的生命周期与 login/logout 相关联。
那么,如果要在注销时释放单例怎么办?我认为这是使用 [weak self]
有用的有效案例,即使对于单身人士也是如此。
否则正如 vadian 所说,DispatchQueue
闭包不会导致保留循环,因为 self 不拥有它们。有关更多信息,请参阅
我看到了 raywenderlich 的教程,作者提供了一些关于处理单例线程问题的好技巧。但是当在单例 class 中使用闭包时,他使用的是 'weak' 引用循环。真的有必要吗,既然 class 是一个单例,它应该总是有一个实例吗?
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
不拥有它们。
基本上不需要单例对象内的捕获列表,因为单例永远不会被释放。
一些单例的生命周期与应用程序生命周期相关联。某些单例的生命周期与 login/logout 相关联。
那么,如果要在注销时释放单例怎么办?我认为这是使用 [weak self]
有用的有效案例,即使对于单身人士也是如此。
否则正如 vadian 所说,DispatchQueue
闭包不会导致保留循环,因为 self 不拥有它们。有关更多信息,请参阅