我在 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)
当调用 setValuesForKeys 时,它会抛出一个异常,内容如下:
*** 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.'
我有关键的“纬度”,但由于某种原因它无法找到它。有任何想法吗!
方式Double!
(相似地Double?
) 在 Objective-C 世界中没有对应关系,所以它不作为 Objective-C 属性公开 https://stackoverflow.com/questions/34793782/swift-this-class-is-not-key-value-coding-compliant-for-double-values,因此键值编码无法找到名为“latitude”的键并崩溃。
如果您需要 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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)