Swift: “This class is not key value coding-compliant…” for Double values

我只是一个虾纸丫 提交于 2019-12-09 13:44:44

问题


I have a scenario in which I have a simple data object in Swift, containing multiple property variables. They are a mix of String? and Double? value types. I'm trying to retrieve the values for each property using valueForKey. My code looks something like this...

let myDataObj = ...
let stringKeyName = "myStringProperty"
let doubleKeyName = "myDoubleProperty"

guard let stringPropertyValue = myDataObj.valueForKey(stringKeyName) else {
    return
}
guard let doublePropertyValue = myDataObj.valueForKey(doubleKeyName) else {
    return
}

The first call to get stringPropertyValue works fine, and I am able to retrieve the value as expected. However, the second call to retrieve doublePropertyValue fails with an exception saying, "this class is not key value coding-compliant for the key myDoubleProperty.'"

I know that the property name is correct, and I also know that a value is set for this property. Why is it that valueForKey works on String objects, but not Double objects?


回答1:


Correct, you can only do key value coding for types that can be represented in Objective-C. Unfortunately, those types that are represented as primitive data types in Objective-C (e.g. Swift's Int and Double are represented as NSInteger and double in Objective-C, respectively) can not be presented as such if they are optionals. In Objective-C, optionals only make sense with class types, not fundamental data types.



来源:https://stackoverflow.com/questions/34793782/swift-this-class-is-not-key-value-coding-compliant-for-double-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!