在包含@字符的键的NSDictionary中获取valueForKey时出错 [英] Error getting valueForKey in an NSDictionary for key containing @ character
问题描述
我试图在名为robotDesign的以下NSDictionary中获取@type键的值
{
@id=2;
@type=piggyDash;
turnAngle =-90;
width =90.0;
}
这是我使用的JSON对象的一部分
[NSJSONSerialization JSONObjectWithData:options:error:];
我使用以下代码提取@type值
NSString * robot_type =(NSString *)[robotDesign valueForKey:@@ type];
但回收以下错误:
由于未捕获异常而终止应用程序'NSUnknownKeyException',
请注意,字典中的其他对象(如turnAngle和width)
原因:'[< __ NSCFDictionary 0x71de9e0> valueForUndefinedKey:]:此
类不是键值编码符合键类型。解决方案尝试
NSString * robot_type = [robotDesign objectForKey:@@ type];
或移除领先的
@
valueForKey:
返回与给定键相关联的值。
- (id)valueForKey: (NSString *)键
参数键要为其返回相应值的键。注意,当使用键值编码时,
键必须是字符串(参见键值编码基础)。
返回值
与键相关联的值。
讨论如果键不以@开头,请调用objectForKey :.如果
键以@开头,则删除@并使用键的其余部分调用[super
valueForKey:]。
@
导致调用超类的valueForKey:
NSDictionary。但NSObject不知道关键字类型
的任何东西。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.
解决方案try
NSString * robot_type = [robotDesign objectForKey:@"@type"];
or remove the leading
@
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 thevalueForKey:
of the superclass of NSDictionary. But NSObject does not know anything about the keytype
.这篇关于在包含@字符的键的NSDictionary中获取valueForKey时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!