2012-08-04 85 views
1

Possible Duplicate:
Using valueForKeyPath on NSDictionary if a key starts the @ symbol?爲什麼[dict valueForKey:@「@」]會導致SIGABRT?

錯誤:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: 
'[<__NSDictionaryI 0x100110e00> valueForUndefinedKey:]: 
this class is not key value coding-compliant for the key .' 

示例代碼:

NSDictionary *dict = @{ @"foo": @"bar" }; 

NSLog(@"foo=%@, qaz=%@", [dict valueForKey:@"foo"], [dict valueForKey:@"qaz"]); 
NSLog(@"@=%@", [dict valueForKey:@"@"]); // SIGABRT 

使用[dict objectForKey:@"@"]時也會發生這種情況。

即使在「@」鍵定義它還是引起了SIGABRT

NSDictionary *dict = @{ @"@": @"at-sign" }; 
NSLog(@"@=%@", [dict valueForKey:@"@"]); // SIGABRT 

這究竟是爲什麼,以及如何我可以檢索從詞典中「@」鍵的值?

回答

5

當您嘗試訪問字典中的對象時,您應該使用objectForKey:valueForKey:valueForKeyPath:方法適用於KVC並且對它們的命名有一些限制。使用[dict objectForKey:@"@"]將工作併爲您的示例返回(null)at-sign

+0

仍然SIGABRT似乎很激烈:( – 2012-08-04 22:30:44

+0

@ pst嗯,那是什麼情況,如果你不處理異常... ... – JustSid 2012-08-04 22:52:42