Realm notifications that capture [weak self] in Swift

馋奶兔 提交于 2019-12-24 02:47:04

问题


In the Realm documentation for Swift, the section on notifications has this sample code:

class ViewController: UITableViewController {
  var notificationToken: NotificationToken? = nil

  override func viewDidLoad() {
    super.viewDidLoad()
    let realm = try! Realm()
    let results = realm.objects(Person.self).filter("age > 5")

    // Observe Results Notifications
    notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
      guard let tableView = self?.tableView else { return }
      // ... some code removed here ...
    }
  }

  deinit {
    notificationToken?.stop()
  }
}

I was wondering why [weak self] is used here instead of [unowned self]. In what use case could self be nil here? (before reaching deinit)


回答1:


In this specific case it cannot be ever nil because the notification block will never be called after stop() is called, and unowned would be fine. The use of weak is just to make it more robust in the case where someone copies and pastes the code into a seemingly similar situation which does not actually guarantee that self will never be nil.



来源:https://stackoverflow.com/questions/39525752/realm-notifications-that-capture-weak-self-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!