2017-02-24 68 views
0

我有3个通知:通知中心swift3无法观察后

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)

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

updateUx func只包含通知的打印。

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

+0

您无法收到第一个通知。你没有注意'Notification1',但是你正在观察'DashboardNotification' – viral

+0

你确定名字是要添加观察者和post观察者是一样的吗? – Priyal

+0

尝试更改'NotificationCenter.default.addObserver',如下所示。它应该工作。我试过了,它确实如此。 – viral

回答

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