NotificationCenter swift3 Can't observe post

2019-06-14 11:24发布

I have 3 notifications:

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)

And I have for each post one differents observer in view controller

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

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

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

updateUx func contain only a print of notification.

I only got my first notification I cannot catch the two other, I don't know why.

1条回答
萌系小妹纸
2楼-- · 2019-06-14 11:39

Add your observers like following:

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)

And you are good to go.


EDIT: Full source code (This project has a UIButton on view and the @IBAction is connected to it in storyboard. On tapping that button, all 3 notifications will get posted. The log is supposed to get printed thrice in console)

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...")
    }
}
查看更多
登录 后发表回答