【发布时间】:2020-11-07 14:09:46
【问题描述】:
我有以下代码,我在其中创建了一个充当默认通知观察者的类。但是通知永远不会到达:
struct NotificationCenterExampleView: View {
let observerA = ObserverClassA()
init() {
print("NotificationCenterExampleView init")
NotificationCenter.default.addObserver(observerA, selector: #selector(ObserverClassA.receivedNotification(notification:)), name: Notification.Name("CustomNotification"), object: "This is the message")
let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "Message being sent", userInfo: nil)
NotificationCenter.default.post(notificationToPost)
}
var body: some View {
Text("Notification Center Example")
.frame(minWidth: 250, maxWidth: 500, minHeight: 250, maxHeight: 500)
}
}
class ObserverClassA: NSObject {
@objc func receivedNotification(notification: Notification) {
let message = notification.object as! String
print("Message received: \(message)")
}
}
我知道使用 .publisher 和 onReceive 这将在 View 结构中工作,但是这段代码不起作用的实际原因是什么?
【问题讨论】:
标签: swift swiftui nsnotificationcenter