Should notification be removed using self in iOS?
Team mate have registered a notification in viewWillAppear
and removed in viewDidDisappear
like,
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self
because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self)
by accident or by developers mistake. My suggestion was to remove observer using,
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}
Team mates replied that removing with NotificationCenter.default.removeObserver(self)
is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self
.
Is there any guideline from Apple about best practice of removing notification observers?
Aucun commentaire:
Enregistrer un commentaire