在另一个线程中修改时,观察Swift 4中的NSManagedObject会导致崩溃吗?

时间:2018-03-30 03:00:26

标签: swift observable nsmanagedobject

我有什么:

NSManagedObject,当从CoreData

中删除动态属性时,将其设置为true
override func prepareForDeletion() {
    super.prepareForDeletion()
    hasBeenDeleted = true
}

在视图中,我使用Swift 4的新Observe模式观察这个NSManagedObject

// I added this to observe the OBSERVED deletion to avoid a crash similar to:
// "User was deallocated while key value observers were still registered with it."
private var userDeletionObserver: NSKeyValueObservation?
  private func observeUserDeletion() {
    userDeletionObserver = user?.observe(\.hasBeenDeleted, changeHandler: { [weak self] (currentUser, _) in
      if currentUser.hasBeenDeleted {
        self?.removeUserObservers()
      }
    })
  }

  private func removeUserObservers() {
    userDeletionObserver = nil
    userObserver = nil
  }

  private var userObserver: NSKeyValueObservation?
  private var user: CurrentUser? {
    willSet {
      // I remove all observers in willSet to also cover the case where we try to set user=nil, I think it's safer this way.
      removeUserObservers()
    }
    didSet {
      guard let user = user else { return }
      // I start observing the NSManagedObject for Deletion
      observeUserDeletion()
      // I finally start observing the object property
      userObserver = user.observe(\.settings, changeHandler: { [weak self] (currentUser, _) in
        guard !currentUser.hasBeenDeleted else { return }
        self?.updateUI()
      })
    }
  }

现在,这里有一个观察和问题:

观察:即使我没有执行observeUserDeletion事情,该应用程序似乎也能正常运行,因此可能没有必要,但因为我有另一个与observe()相关的崩溃模式我试着过分小心。

问题详情:我是否真的需要关心OBSERVED对象在被观察时随时变为nil,或者当OBSERVED对象被'nilled时,新的Swift 4观察模式会自动删除观察者“?

0 个答案:

没有答案