简体   繁体   English

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

[英]Swift Combine: Could not extract a String from KeyPath Swift.KeyPath

I'm trying to observer any changes in object in the core data instance.我试图观察核心数据实例中对象的任何变化。 Here is my code:这是我的代码:

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

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

Here is were I'm implementing the observers:这是我正在实施观察者:

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

But I'm getting this error:但我收到此错误:

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

在此处输入图片说明

Any of you knows why I'm getting this error or if there is any work around ?你们中的任何人都知道为什么我会收到此错误或者是否有任何解决方法?

I'll really appreciate your help.我会非常感谢你的帮助。

You are trying to create a publisher that uses key-value observing.您正在尝试创建一个使用键值观察的发布者。 Key-value observing is a feature of the Objective-C runtime.键值观察是 Objective-C 运行时的一个特性。 You have exposed the properties title and summary to the Objective-C runtime by putting @objc and dynamic on them.您已经通过将@objcdynamic放在 Objective-C 运行时公开了属性titlesummary myVar , however, is a plain instance variable, not a observable property.然而, myVar是一个普通的实例变量,而不是一个可观察的属性。 So the key-value coding system can't find it and at runtime you get an error.所以键值编码系统找不到它,在运行时你会得到一个错误。

The documentation at文档位于

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

says

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.使用@objc 属性和动态修饰符标记要通过键值观察来观察的属性。

In addition, to participate in key-value coding, MyClass will also have to be available to Objective-C and must have the properties you wish to access from key-key value observing marked too:此外,要参与键值编码,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?
}

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

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