为什么[dict valueForKey:@“@”]会导致SIGABRT?

问题描述:

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 

这究竟是为什么,以及如何我可以检索从词典中“@”键的值?

当您尝试访问字典中的对象时,您应该使用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