0

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

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

4

1 回答 1

4

添加您的观察者,如下所示:

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...")
    }
}
于 2017-02-24T10:57:39.710 回答