NotificationCenter swift3 Can't observe post

馋奶兔 提交于 2019-12-08 10:19:56

问题


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:


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


来源:https://stackoverflow.com/questions/42436651/notificationcenter-swift3-cant-observe-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!