NotificationCenter swift3无法观察帖子

时间:2017-02-24 10:44:49

标签: ios swift swift3 nsnotificationcenter notificationcenter

我有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仅包含通知打印。

我只得到了我的第一个通知,我无法抓住另外两个,我不知道为什么。

1 个答案:

答案 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...")
    }
}