【问题标题】:NotificationCenter - addObserver not calledNotificationCenter - 未调用 addObserver
【发布时间】:2020-07-08 02:46:39
【问题描述】:

我正在尝试使用 NotificationCenter 编写一个非常简单的代码。但是 addObserver 没有被调用。你们中的任何人都可以检查并让我知道我缺少什么。有两个简单的类,一个发布通知,另一个监听它。当我运行程序时,我只在控制台中看到“发送通知”。

提前致谢。

第 1 类:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("sending notification")
        NotificationCenter.default.post(name: Notification.Name("test"), object: nil)
    }
}

第 2 类:

class secondvc: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("second vc")
        NotificationCenter.default.addObserver(self,
            selector: #selector(doThisWhenNotify(_:)),
            name: Notification.Name("test"),
            object: nil)
    }
     
    @objc  func doThisWhenNotify(_ notification: Notification) {
         print("inside notification")
    }
}

【问题讨论】:

  • 您也没有看到“第二个vc”打印出来吗?如果是这种情况,您永远不会初始化您的 secondvc,因此它的 viewDidLoad() 不会被调用。

标签: swift nsnotificationcenter notificationcenter


【解决方案1】:

如果在ViewController 存在时,secondvc 尚不存在,那么那里没有人可以接收发布的通知,这就是为什么您稍后在@ 时看不到收到通知的原因987654323@ 确实成立了。

【讨论】:

  • 谢谢马特。现在知道了...将相应地处理它。
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
相关资源
最近更新 更多