Error getting ForKey value in NSDictionary for key containing @ character

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

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

which is part of the JSON object that I used

 [NSJSONSerialization JSONObjectWithData: options: error:]; 

I use the following code to retrieve @type value

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

but get the following error:

Application termination due to the uncaught exception "NSUnknownKeyException", reason: '[<__NSCFDictionary 0x71de9e0> valueForUndefinedKey:]: this class is not the key for encoding for the key type. ''

NOTE. Note that other objects in the dictionary, such as "turnAngle" and "width", are easily retrieved using the same code as above, but with the corresponding keys.

+6
source share
2 answers

to try

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

or delete lead @

from documents:

valueForKey:
Returns the value associated with the given key.

- (id)valueForKey:(NSString *)key
Parameters Key to return the corresponding value. Please note that when using an encoding key value, the key must be a string (see "Key Value Encoding Basics").

Return value
The value associated with the key.

Discussion If the key does not start with "@", it calls objectForKey :. If the key starts with "@", breaks the "@" and calls [super valueForKey:] with the rest of the key.

@ leads to a call to the implementation of valueForKey: NSDictionary superclass. But NSObject knows nothing about the type key.

+13
source

This is a well documented behavior. From the NSDictionary class reference:

NSDictionary overrides the valueForKey: method. If the key starts with the '@' character, it calls super, otherwise it calls objectForKey:

So, if you have no good reason not to do this, you should use - objectForKey:

+6
source

All Articles