objectForKey與valueForKey在NSDictionary中的差異

從NSDictionary 取值的時(shí)候有兩個(gè)方法,objectForKey: 和 valueForKey:,這兩個(gè)方法具體有什么不同呢?

先從 NSDictionary 文檔中來(lái)看這兩個(gè)方法的定義:

objectForKey: returns the value associated with aKey, or nil if no value is associated with aKey. 返回指定 key 的 value,若沒(méi)有這個(gè) key 返回 nil.
valueForKey: returns the value associated with a given key. 同樣是返回指定 key 的 value。

直觀上看這兩個(gè)方法好像沒(méi)有什么區(qū)別,但文檔里 valueForKey: 有額外一點(diǎn):

If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key. via Discussion

一般來(lái)說(shuō) key 可以是任意字符串組合,如果 key 不是以 @ 符號(hào)開(kāi)頭,這時(shí)候 valueForKey: 等同于 objectForKey:,如果是以 @ 開(kāi)頭,去掉 key 里的 @ 然后用剩下部分作為 key 執(zhí)行 [super valueForKey:]。

比如:


NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue" forKey:@"theKey"];

NSString *value1 = [dict objectForKey:@"theKey"];

NSString *value2 = [dict valueForKey:@"theKey"];

這時(shí)候 value1 和 value2 是一樣的結(jié)果。如果是這樣一個(gè) dict:


NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue" forKey:@"@theKey"];// 注意這個(gè) key 是以 @ 開(kāi)頭

NSString *value1 = [dict objectForKey:@"@theKey"];

NSString *value2 = [dict valueForKey:@"@theKey"];

value1 可以正確取值,但是 value2 取值會(huì)直接 crash 掉,報(bào)錯(cuò)信息:


Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason:

‘[<__NSCFDictionary 0x892fd80> valueForUndefinedKey:]:this class is not key value coding-compliant for the key theKey.’

這是因?yàn)?valueForKey: 是 KVC(NSKeyValueCoding) 的方法,在 KVC 里可以通過(guò) property 同名字符串來(lái)獲取對(duì)應(yīng)的值。比如:


@interface Person : NSObject

@property (nonatomic, retain) NSString *name;

@end

Person *person = [[Person alloc] init];

person.name = @"John Lee";

NSLog(@"name:%@", [person name]);

//name:John Lee

NSLog(@"name:%@", [person valueForKey:@"name"]);

//name:John Lee

[person release];

valueForKey: 取值是找和指定 key 同名的 property accessor,沒(méi)有的時(shí)候執(zhí)行 valueForUndefinedKey:,而 valueForUndefinedKey: 的默認(rèn)實(shí)現(xiàn)是拋出 NSUndefinedKeyException 異常。
回過(guò)頭來(lái)看剛才 crash 的例子, [dict valueForKey:@"@theKey"]; 會(huì)把 key 里的 @ 去掉,也就變成了 [dict valueForKey:@"theKey"];,而 dict 不存在 theKey 這樣的 property,轉(zhuǎn)而執(zhí)行 [dict valueForUndefinedKey:@"theKey"];,拋出 NSUndefinedKeyException 異常后 crash 掉。
objectForKey: 和 valueForKey: 在多數(shù)情況下都是一樣的結(jié)果返回,但是如果 key 是以 @ 開(kāi)頭,valueForKey: 就成了一個(gè)大坑,建議在 NSDictionary 下只用 objectForKey: 來(lái)取值。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容