问题
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