Error getting valueForKey in an NSDictionary for key containing @ character

孤街醉人 提交于 2019-11-26 18:33:09

问题


I am trying to get the value of "@type" key in the following NSDictionary named 'robotDesign'

robotDesign : {
    "@id" = "2";
    "@type" = "piggyDash";
    turnAngle = "-90";
    width = "90.0";
}

that is a part of a JSON object I got using

[NSJSONSerialization JSONObjectWithData: options: error:];

I am using following code to extract @type value

NSString * robot_type = (NSString*)[robotDesign valueForKey:@"@type"];

but recive following error:

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

NOTE: Please note that other objects in dictionary like 'turnAngle' and 'width' are extracted easily using same code given above but with their respective keys.


回答1:


try

NSString * robot_type = [robotDesign objectForKey:@"@type"];

or remove the leading @

from the docs:

valueForKey:
Returns the value associated with a given key.

- (id)valueForKey:(NSString *)key
Parameters key The key for which to return the corresponding value. Note that when using key-value coding, the key must be a string (see “Key-Value Coding Fundamentals”).

Return Value
The value associated with key.

Discussion 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.

The @ leads to call the implementation of the valueForKey: of the superclass of NSDictionary. But NSObject does not know anything about the key type.




回答2:


This is perfectly documented behavior. From NSDictionary's class reference:

NSDictionary overrides the 'valueForKey:' method. If the key starts with an '@' character, it invokes super, else it invokes objectForKey:

So, unless you have a valid reason for not doing so, you should use - objectForKey:.



来源:https://stackoverflow.com/questions/13294696/error-getting-valueforkey-in-an-nsdictionary-for-key-containing-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!