我有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)
对于每个帖子,我在视图控制器中有一个不同的观察者
第一: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 func仅包含通知打印。
我只得到了我的第一个通知,我无法抓住另外两个,我不知道为什么。
答案 0 :(得分:3)
添加您的观察者,如下所示:
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
,@IBAction
在故事板中与它相连。点击该按钮后,所有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...")
}
}