为什么我无法在 SwiftUI 的视图结构内收到有关观察者 class 的通知?
Why I can't receive a notification on an observer class inside a View struct in SwiftUI?
我有以下代码,我在其中创建了一个 class 作为默认通知的观察者。但通知从未到达:
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 结构中工作,但这段代码不起作用的真正原因是什么?
通知与对象匹配,因此如果您订阅一个对象但 post 订阅另一个对象,则不会触发订阅者。
这里是固定变体。使用 Xcode 12.1.
进行测试
NotificationCenter.default.addObserver(observerA,
selector: #selector(ObserverClassA.receivedNotification(notification:)),
name: Notification.Name("CustomNotification"),
object: nil) // << subscribe for all
let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "This is the message", userInfo: nil)
NotificationCenter.default.post(notificationToPost)
我有以下代码,我在其中创建了一个 class 作为默认通知的观察者。但通知从未到达:
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 结构中工作,但这段代码不起作用的真正原因是什么?
通知与对象匹配,因此如果您订阅一个对象但 post 订阅另一个对象,则不会触发订阅者。
这里是固定变体。使用 Xcode 12.1.
进行测试 NotificationCenter.default.addObserver(observerA,
selector: #selector(ObserverClassA.receivedNotification(notification:)),
name: Notification.Name("CustomNotification"),
object: nil) // << subscribe for all
let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "This is the message", userInfo: nil)
NotificationCenter.default.post(notificationToPost)