试图在可观察对象发生更改时发布通知。
这似乎是错误的。寻找更好的方法。
class MyClass: ObservableObject {
@Published var date: Date {
didSet {
NotificationCenter.default.post(name: .modified, object: self) // want to also post notifications for changes, not just publish to owners of the object
}
}
@Published var a: Int {
didSet {
NotificationCenter.default.post(name: .modified, object: self)
}
}
@Published var b: Int {
didSet {
NotificationCenter.default.post(name: .modified, object: self)
}
}
}
如果我正确理解您的意图,解决方案是订阅默认发布者,该发布者发布任何更改的事件,即
class MyClass: ObservableObject {
@Published var date: Date = Date() // default values just for demo simplicity
@Published var a: Int = 0
@Published var b: Int = 0
private var subscriber: AnyCancellable!
init() {
subscriber = self.objectWillChange.sink { [weak self] in
guard let object = self else { return }
NotificationCenter.default.post(name: .modified, object: object)
}
}
}