3

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?.invalidate() in Realm 10.12
    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)

XY L
  • 25,431
  • 14
  • 84
  • 143
Steven Vandeweghe
  • 2,170
  • 2
  • 20
  • 24
  • Apple said "Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization." – larva Sep 16 '16 at 07:30
  • maybe your answer here http://stackoverflow.com/questions/24468336/how-to-correctly-handle-weak-self-in-swift-blocks-with-arguments – larva Sep 16 '16 at 07:34

1 Answers1

3

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.

Thomas Goyne
  • 8,010
  • 32
  • 30