Swift KVO持有对象引用计数

Swift KVO holding object reference count

我在 swift 代码中添加观察者如下:

private var keyValueObservations = [NSKeyValueObservation]()

然后在代码中

  let keyValueObservation = session.observe(\.isRunning, options: .new) { _, change in
          guard let isSessionRunning = change.newValue else { return }

          DispatchQueue.main.async {[weak self] in
            //  self.recordButton.isEnabled = isSessionRunning
            self?.delegate?.cameraSessionStartedRunning(session: self?.session)
          }
      }
      keyValueObservations.append(keyValueObservation)

然后

 private func removeObservers() {
      for keyValueObservation in keyValueObservations {
          keyValueObservation.invalidate()
      }

      keyValueObservations.removeAll()
  }


 deinit {
      removeObservers()
      NSLog("Calling deinit on \(type(of: self))")
  }

问题是这似乎保留了 self 的引用计数,因此无法通过将其设置为 nil 来释放对象。结果永远不会调用 Deinit。我该如何解决?

这里的问题是你捕捉自我的时间比你想象的要早。这应该可以解决它:

let keyValueObservation = session.observe(\.isRunning, options: .new) { [weak self] _, change in
    guard let isSessionRunning = change.newValue else { return }

    DispatchQueue.main.async { [weak self] in
        //  self.recordButton.isEnabled = isSessionRunning
        self?.delegate?.cameraSessionStartedRunning(session: self?.session)
    }
}
keyValueObservations.append(keyValueObservation)

所以你看到它是在分派回主线程时捕获 self 的观察者函数的闭包。