Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

objective c - Error getting valueForKey in an NSDictionary for key containing @ character

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...