ios - 即使我在 viewWillAppear 中注册并在 viewWillDissapear 中取消注册,也会多次调用观察者方法
问题描述
即使我在 viewWillAppear 中注册并在 viewWillDissapear 中取消注册,观察者方法也会被多次调用。
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self,
selector: #selector(handlePushNotification(notification:)),
name: NSNotification.Name(rawValue: "abc"),
object: nil)
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "abc"), object: nil)
}
解决方案
对于具有属性观察者的成员变量,这是一个很好的用例:只需让通知观察者成为 View Controller 子类的成员,并在 willSet 块内处理通知观察者的清理:
class MyViewController: UIViewController {
var notificationObserver: Any? {
willSet {
// if notificationObserver is not null, unregister it
if let observer = notificationObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
override func viewWillAppear(_ animated: Bool) {
notificationObserver = NotificationCenter.default.addObserver(self,
selector: #selector(handlePushNotification(notification:)),
name: NSNotification.Name(rawValue: "abc"),
object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
notificationObserver = nil
}
}
这将确保现有观察者在创建新观察者时始终未注册。
如果您仍然收到多个回调,则意味着通知被多次发送。
推荐阅读
- android - 足以生成 GeoJSON 的最小数据量?
- android - PWABuilder Android 包“找不到系统 Java 编译器”。
- powershell - 如何为网站绑定选择新安装的 SSL 证书
- angular - 胖箭头函数的这两种语法之间是否有区别,或者它们在功能上是否相同?
- python - Django 中的查询集联合
- image - 编码新手和背景图像有问题
- django - 通过 init 自定义 Django Admin 的 verbose_name,使用默认值
- spring - Whitelabel 错误页面 - 此应用程序没有 /error 的显式映射,因此您将其视为后备
- php - 使用 Woocommerce 中的复选框从 mailchimp 的结帐页面收集电子邮件
- reactjs - 无法使用 dom-testing-library 从作为其父标签的标签访问输入