问题
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