gpt4 book ai didi

objective-c - 在 NSDictionary 中获取包含 @ 字符的键的 valueForKey 时出错

转载 作者:可可西里 更新时间:2023-11-01 03:36:47 26 4
gpt4 key购买 nike

我正在尝试在名为“robotDesign”的以下 NSDictionary 中获取“@type”键的值

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

这是我使用的 JSON 对象的一部分

[NSJSONSerialization JSONObjectWithData: options: error:];

我正在使用以下代码提取@type 值

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

但收到以下错误:

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

注意:请注意,字典中的其他对象(如“turnAngle”和“width”)可以使用上面给出的相同代码轻松提取,但使用它们各自的键。

最佳答案

尝试

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

或删除前导的@

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.

@ 导致调用NSDictionary 父类(super class)的valueForKey: 的实现。但是 NSObject 对 type 键一无所知。

关于objective-c - 在 NSDictionary 中获取包含 @ 字符的键的 valueForKey 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com