2017-04-03 45 views
3

我在操場下面的代碼:setValueForKeys失敗斯威夫特

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.' 

我有鑰匙「緯度」,但由於某種原因,它無法找到它。有任何想法嗎!

SOLUTION:閱讀選擇的答案,這裏是更新後的代碼:

class Pokemon : NSObject { 

    var name :String! 
    var id :Int = 0 
    var imageURL :String! 
    var latitude :Double = 0 
    var longitude :Double = 0 

    init(dictionary :[String:Any]) { 

     super.init() 
     setValuesForKeys(dictionary) 
} 
} 
+3

爲什麼要創建這樣的初始化程序?爲什麼不創建適當的初始化程序或直接設置屬性? – rmaddy

+0

絕對!但是我想知道我在上面的代碼中做錯了什麼。另外,如果你設置了很多屬性,這個初始化器會很有幫助。 –

+0

那麼[this one](http://stackoverflow.com/q/26366082/3476191)呢? – NobodyNada

回答

5

類型Double!(類似Double?)在Objective-C的世界中沒有對應關係,所以it is not exposed as an Objective-C property,所以鍵 - 值編碼不能找到一個名爲「緯度」的關鍵並崩潰。

如果您需要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) 
    } 
} 
+0

和絃!或字符串?在Objective-C世界中有對應關係。 –

+0

@johndoe是的,那些在ObjC中變成'NSMutableString *'。 – kennytm