I have the following code in the Playground:
class Pokemon : NSObject {
var name :String!
var id :Int?
var imageURL :String!
var latitude :Double!
var longitude :Double!
init(dictionary :[String:Any]) {
super.init()
setValuesForKeys(dictionary)
}
}
let dict :[String:Any] = ["name":"John","imageURL":"someimageURL","latitude":45.67]
let pokemon = Pokemon(dictionary: dict)
When the call to setValuesForKeys is made then it throws an exception saying the following:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__lldb_expr_13.Pokemon 0x6000000ffd00> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key latitude.'
I have the key "latitude" but for some reason it is not able to find it. Any ideas!
The type Double!
(similarly Double?
) has no correspondence in the Objective-C world, so it is not exposed as an Objective-C property , so Key-Value Coding cannot find a key named "latitude" and crash.
You should convert those fields to non-optional if you need KVC.
class Pokemon : NSObject {
var name: String!
var id: Int = 0
var imageURL: String!
var latitude: Double = 0.0
var longitude: Double = 0.0
init(dictionary: [String: Any]) {
super.init()
setValuesForKeys(dictionary)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.