问题描述
在Swift的Realm文档中,通知部分具有此示例代码:
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()
}
}
我想知道为什么在这里使用[weak self]
而不是[unowned self]
.在什么情况下self
可以为零? (在到达deinit
之前)
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
)
推荐答案
在这种特定情况下,它永远不会成为nil
,因为在调用stop()
之后永远不会调用通知块,并且unowned
就可以了.在某些人将代码复制并粘贴到看似相似的情况下,实际上并不能保证self
永远不会是nil
.
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
.
这篇关于在Swift中捕获[弱自我]的领域通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!