【发布时间】: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