NotificationCenter swift3 无法观察 post

NotificationCenter swift3 Can't observe post

我有 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)

我在视图控制器中为每个 post 设置了一个不同的观察者

第一: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 视图,@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...")
    }
}