如何 post 当可观察对象发生变化时发出通知

How to post a notification when an observable object has changed

尝试在可观察对象发生变化时post发出通知。

这似乎是错误的。寻找更好的方法。

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)
        }
    }
}