從 NSDictionary 取值的時候有兩個方法,objectForKey: 和 valueForKey:,這兩個方法具體有什么不同呢?
以實例說明:
1 NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue"forKey:@"theKey"]; 2 NSString *value1 = [dict objectForKey:@"theKey"]; 3 NSString *value2 = [dict valueForKey:@"theKey"];
這時候 value1 和 value2 是一樣的結果。如果是這樣一個 dict:
1 NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue" forKey:@"@theKey"];// 注意此處key是以@開頭 2 NSString *value1 = [dict objectForKey:@"@theKey"]; 3 NSString *value2 = [dict valueForKey:@"@theKey"];
value1 可以正確取值,但是 value2 取值會直接 crash 掉,報錯信息:
Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[<__NSCFDictionary 0x892fd80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key theKey.’
這是因為 valueForKey: 是 KVC(NSKeyValueCoding) 的方法,在 KVC 里可以通過 property 同名字符串來獲取對應的值。比如:
valueForKey: 取值是找和指定 key 同名的 property accessor,沒有的時候執行 valueForUndefinedKey:,而 valueForUndefinedKey: 的默認實現是拋出 NSUndefinedKeyException 異常。
回過頭來看剛才 crash 的例子, [dict valueForKey:@"@theKey"]; 會把 key 里的 @ 去掉,也就變成了 [dict valueForKey:@"theKey"];,而 dict 不存在 theKey 這樣的 property,轉而執行 [dict valueForUndefinedKey:@"theKey"];,拋出 NSUndefinedKeyException 異常后 crash 掉。
objectForKey: 和 valueForKey: 在多數情況下都是一樣的結果返回,但是如果 key 是以 @ 開頭,valueForKey: 就成了一個大坑,建議在 NSDictionary 下只用 objectForKey: 來取值。