swift - 为什么我无法在 SwiftUI 中的 View 结构内收到有关观察者类的通知?
问题描述
我有以下代码,我在其中创建了一个充当默认通知观察者的类。但是通知永远不会到达:
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
andonReceive
这将在 View 结构中工作,但是这段代码不起作用的实际原因是什么?
解决方案
由对象匹配的通知,因此如果您订阅一个对象但使用另一个对象发布,则不会触发订阅者。
这是固定的变体。使用 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)
推荐阅读
- census - 美国州际移民流动
- typescript - TypeScript:如何根据另一个泛型推断一个泛型的类型?
- node.js - 使用 nodejs 访问自定义 HTTP 标头
- r - R如果每行的最大值为负,则将字符串添加到colnames
- css - 对带有 XSLT 的样式表使用相对 href 不适用于 macOS WebView (Xamarin.Forms 5.x)
- python - 你可以直接定义 __doc__ 吗?
- winforms - WinForms:DevExpress:GridView:鼠标双击打开表单
- redirect - 如何将流量重定向到 cisco 交换机 3750 上的另一个接口?
- r - 如果满足特定条件,则删除数据框中的行,同时更新关联的总值
- mysql - 如何显示结果 - MySQL 问题