【问题标题】:Notification Center Observer Selector Method does not get called通知中心观察者选择器方法没有被调用
【发布时间】:2018-12-14 14:56:05
【问题描述】:

我在 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)

任何帮助将不胜感激。

【问题讨论】:

  • addObserver 行中的closButtonPressed(notification:) 前面添加self.
  • 试过了。不工作
  • 嗯,只是为了确定。 addObserverclosButtonPressed 在控制器 A 中。而 post 在控制器 B 中?
  • 在命名 Notification ala NSNotification.Name(rawValue: "CloseButtonPressed")时也尝试使用原始值
  • 是的。我认为有一些与演示有关的东西。我正在使用第三方图像查看器来显示图像。当解雇它时,我需要采取行动。这是第三方链接:github.com/aFrogleap/SimpleImageViewer

标签: ios swift notificationcenter


【解决方案1】:

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

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

}

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案3】:

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

          //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关闭时,发布通知并关闭,控制台可以打印通知对象,所以我会错过什么吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-02
        • 1970-01-01
        相关资源
        最近更新 更多