gpt4 book ai didi

ios - 即使我在 viewWillAppear 中注册并在 viewWillDissapear 中注销,观察者方法也会被多次调用

转载 作者:行者123 更新时间:2023-11-30 11:05:31 24 4
gpt4 key购买 nike

即使我在 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 block 内处理通知观察者的清理:

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
}

}

这将确保在创建新观察者时,现有观察者始终处于未注册状态。

如果您仍然收到多个回调,则意味着通知已发送多次。

关于ios - 即使我在 viewWillAppear 中注册并在 viewWillDissapear 中注销,观察者方法也会被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52780178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com