为什么[dict valueForKey:@"@"]导致SIGABRT?

Tyi*_*ilo 1 macos objective-c

可能重复:
如果一个键启动@符号,则在NSDictionary上使用valueForKeyPath?

错误:

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

示例代码:

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

NSLog(@"foo=%@, qaz=%@", [dict valueForKey:@"foo"], [dict valueForKey:@"qaz"]);
NSLog(@"@=%@", [dict valueForKey:@"@"]); // SIGABRT
Run Code Online (Sandbox Code Playgroud)

使用时也会发生这种情况[dict objectForKey:@"@"].

即使定义了"@"键,它仍会导致SIGABRT:

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

为什么会发生这种情况?如何从字典中检索"@"键的值?

Jus*_*Sid 5

您应该使用objectForKey:试图访问字典对象时,则valueForKey:valueForKeyPath:方法都是为了KVC和对他们的命名有一些限制.使用[dict objectForKey:@"@"]将工作并返回(null)at-sign为您的示例.