【问题标题】:Is it required to to use weak reference's within a singleton class?是否需要在单例类中使用弱引用?
【发布时间】: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()
            }
        }



      }

    }

The tutorial

【问题讨论】:

标签: swift memory-management singleton grand-central-dispatch weak-references


【解决方案1】:

DispatchQueue 闭包的情况下,根本不添加任何捕获列表,无处。

DispatchQueue 闭包不会导致保留循环,因为self 不拥有它们。

基本上不需要在单例对象中捕获列表,因为单例永远不会被释放。

【讨论】:

  • "因为单例永远不会被释放。"如果单例在注销时被释放怎么办?
  • @Honey 注销是什么意思?
  • 退出应用程序。例如你有一个刷新令牌的单例。注销/注销时不再需要该单例
  • @Honey 您不能使用标准 static let shared = 属性解除分配单例。如果您需要一个 volatile 实例,则单例不是正确的选择。
【解决方案2】:

某些单例的生命周期与 App 生命周期相关联。一些单例的生命周期与登录/注销有关。

那么如果单例在注销时被释放呢?我认为这是使用[weak self] 可能有用的有效案例,即使对于单身人士也是如此。

否则正如 vadian 所说,DispatchQueue 闭包不会导致保留周期,因为 self 不拥有它们。更多内容见here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多