是否需要在单例类中使用弱引用?

Jee*_*n_7 3 singleton memory-management weak-references grand-central-dispatch swift

我遇到了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()
            }
        }



      }

    }
Run Code Online (Sandbox Code Playgroud)

本教程

vad*_*ian 5

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

DispatchQueue闭包不会引起保留周期,因为self它不拥有它们。

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