gpt4 book ai didi

ios - NotificationCenter swift3 无法观察帖子

转载 作者:行者123 更新时间:2023-11-28 10:57:32 26 4
gpt4 key购买 nike

我有 3 个通知:

NotificationCenter.default.post(name:NSNotification.Name("Notification1"), object: nil)
NotificationCenter.default.post(name:NSNotification.Name("Notification2"), object: nil)
NotificationCenter.default.post(name:NSNotification.Name("Notification3"), object: nil)

我在 View Controller 中为每个帖子设置了一个不同的观察者

首先:NotificationCenter.default.addObserver(forName:NSNotification.Name("Notification1"), object: nil, queue: nil, using: updateUx)

第二个:NotificationCenter.default.addObserver(forName:NSNotification.Name("Notification2"), object: nil, queue: nil, using: updateUx)

第三:NotificationCenter.default.addObserver(forName:NSNotification.Name("Notification3"), object: nil, queue: nil, using: updateUx)

updateUx 函数仅包含通知打印。

我只收到我的第一个通知我无法捕捉到另外两个,我不知道为什么。

最佳答案

像下面这样添加你的观察者:

NotificationCenter.default.addObserver(self, selector: #selector(updateUx), name: NSNotification.Name("Notification1"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateUx), name: NSNotification.Name("Notification2"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateUx), name: NSNotification.Name("Notification3"), object: nil)

一切顺利。


编辑: 完整的源代码(这个项目有一个 UIButton View 和 @IBAction 在 Storyboard 中连接到它。点击那个按钮,将发布所有 3 个通知。日志应该在控制台中打印三次)

class ViewController: UIViewController {

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(updateUx), name: NSNotification.Name("Notification1"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateUx), name: NSNotification.Name("Notification2"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateUx), name: NSNotification.Name("Notification3"), object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}

@IBAction func abc (_ sender: UIButton) {
NotificationCenter.default.post(name:NSNotification.Name("Notification1"), object: nil)
NotificationCenter.default.post(name:NSNotification.Name("Notification2"), object: nil)
NotificationCenter.default.post(name:NSNotification.Name("Notification3"), object: nil)
}

func updateUx(){
print("received...")
}
}

关于ios - NotificationCenter swift3 无法观察帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42436651/

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