简体   繁体   English

KVO 发布者不发送关于属性更改的信号

[英]KVO publisher does not send signal on property change

I've just started learning Combine and am quite confused with behaviour of KVO publishers.我刚刚开始学习 Combine,对 KVO 发布者的行为感到很困惑。 They just do not publish any events except for the initial value.他们只是不发布任何事件,除了初始值。 Here is the sample code I used:这是我使用的示例代码:

@objc class SampleClass: NSObject {
    @objc var name: NSString = "1"
}

var a = SampleClass()

let kvoPublisher = a.publisher(for: \.name)
    .sink(receiveCompletion: {
        print("completion \($0)")
    }, receiveValue: { newVal in
        print("new val - \(newVal)")
    })

a.name = "2"
a.name = "3"

print("Finished; publisher = \(kvoPublisher) | a.name = \(a.name)")

The console output is控制台输出是

new val - 1
Finished; publisher = Combine.AnyCancellable | a.name = 3

Could you please explain what am I missing here and how to fix it?您能否解释一下我在这里缺少什么以及如何解决?

Thanks.谢谢。

You also need to mark the property as dynamic in order for it to be KVO compliant.您还需要将属性标记为dynamic ,以使其符合 KVO。 publisher(for:) only works with KVO compliant properties, since it uses KVO under the hood. publisher(for:)仅适用于符合 KVO 的属性,因为它在底层使用了 KVO。

@objc class SampleClass: NSObject {
    @objc dynamic var name: NSString = "1"
}

Once you do that, the KVO publisher emits the updated values as expected.一旦你这样做了,KVO 发布者就会按预期发出更新的值。

For more information on @objc vs @objc dynamic , see this Q&A .有关@objc@objc dynamic的更多信息,请参阅此问答

Bear in mind that you should only use KVO publishers when interacting with code that you cannot change.请记住,您应该只在与无法更改的代码交互时使用 KVO 发布者。 When you want to observe property values of types that you control, use @Published instead.当您想观察您控制的类型的属性值时,请改用@Published

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM