Swift 合并:无法从 KeyPath 中提取字符串 Swift.KeyPath

Swift Combine: Could not extract a String from KeyPath Swift.KeyPath

我试图观察核心数据实例中对象的任何变化。这是我的代码:

class MyClass {
    @objc dynamic var str: String?
}

final class Article: NSObject {
    @objc dynamic var title: String?
    @objc dynamic var summary: String?
    var myVar: MyClass?
}

这是我正在实施的观察者:

func update(article: Article) {
    titleSubscription = article.publisher(for: \.title).sink { value in
        print(value)
    } receiveValue: { _ in
        print("I got something")
    }
    summarySubscription = article.publisher(for: \.myVar?.str).sink{ _ in
        
    } receiveValue: { _ in
        
    }
}

但是我收到这个错误:

Thread 1: Fatal error: Could not extract a String from KeyPath Swift.KeyPath<Examples.Article, Swift.Optional<Swift.String>>

你们中有人知道为什么我会收到此错误或者是否有任何解决方法?

非常感谢你的帮助。

您正在尝试创建一个使用键值观察的发布者。键值观察是 Objective-C 运行时的一项功能。通过将 @objcdynamic 放在 titlesummary 属性上,您已将属性 titlesummary 公开给 Objective-C 运行时。然而,myVar 是一个普通的实例变量,而不是可观察的 属性。所以键值编码系统找不到它,在运行时你会得到一个错误。

文档位于

https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift/

Annotate a Property for Key-Value Observing

Mark properties that you want to observe through key-value observing with both the @objc attribute and the dynamic modifier.

此外,要参与键值编码,MyClass 也必须对 Objective-C 可用,并且还必须标记您希望通过键值观察访问的属性:

class MyClass : NSObject {
    @objc dynamic var str: String?
}

final class Article: NSObject {
    @objc dynamic var title: String?
    @objc dynamic var summary: String?
    @objc dynamic var myVar: MyClass?
}