我正在用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")
}
}发布于 2020-07-08 03:05:48
如果在ViewController出现时,secondvc还不存在,那么就没有人可以接收发布的通知,这就是为什么当secondvc确实存在时,您没有看到稍后收到通知的原因。
https://stackoverflow.com/questions/62786769
复制相似问题