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

问题描述 投票:3回答:2

我遇到了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
2个回答
5
投票

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

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

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


0
投票

某些单身人士的生命周期与App生命周期息息相关。一些单身人士的生命周期与登录/注销有关。

那么,如果注销时要释放单身人士怎么办?我认为使用[weak self]是有用的,即使是单身人士也是如此。

[否则正如vadian所说,DispatchQueue闭包不会引起保留周期,因为self不拥有它们。有关更多信息,请参见here

© www.soinside.com 2019 - 2024. All rights reserved.