通知中心观察者选择器方法未调用

时间:2018-12-14 05:43:15

标签: ios swift notificationcenter

我在A视图控制器上添加了一个观察者,而视图控制器B在A上呈现。

关闭控制器B时,我已发布了通知,但未调用A中添加的选择器方法。

还先注册通知,然后调用post方法。我已经检查过了。

这是示例代码:

NotificationCenter.default.addObserver(self, selector: #selector(closButtonPressed(notification:)) ,name: Notification.Name("CloseButtonPressed"), object: nil)


@objc func closButtonPressed(notification: Notification){
}

NotificationCenter.default.post(name: Notification.Name("CloseButtonPressed"), object: self)

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

确保在完成处理程序中发布通知

self?.dismiss(animated: true, completion: {
NotificationCenter.default.post(name: Notification.Name("CloseButtonPressed"), 
object: self)

}

答案 1 :(得分:0)

确保正确实施通知。我建议您为“通知名称”创建一个扩展名并将其设置为静态。

extension Notification.Name {
    static let didTapCloseButton = Notification.Name("CloseButtonPressed")
}

NotificationCenter.default.addObserver(self, selector: #selector(didTapCloseButton(_:)), name: .didTapCloseButton, object: nil)

@objc func didTapCloseButton(_ sender: Notification?) {

}

NotificationCenter.default.post(name: .didTapCloseButton, object: nil)

答案 2 :(得分:0)

我不确定您的项目出了什么问题。为了解决您的问题,我创建了一个测试项目并编写了以下代码:

    //ControllerA.swift
    override func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(getNotification(notification:)), name:      NSNotification.Name("CloseButtonPressed"), object: nil)
    }

    getNotification(notification: Notification) {
    print(notification)
    }

    @objc func buttonAClick() {
        navigationController?.present(ViewControllerB(), animated: true, completion: {
        })
    }

    //ViewControllerB.swift
    @objc func buttonClick() {
            NotificationCenter.default.post(name: Notification.Name("CloseButtonPressed"), object: self)
            self.dismiss(animated: true) {
            }
        }

正如您所说,我在ControllerA中添加了通知,并提供了ControllerB,当ControllerB关闭,发布通知并关闭时,控制台可以打印通知对象,所以我可能会错过什么吗?