如何从NSDictionary获取整数值?

Jam*_*mes 22 json objective-c ios

我有这个奇怪的问题.NSDictionary未返回正确的整数值.

来自服务器的JSON响应代码.

{
"status":"ok",
"error_code":0,
"data" : [],
"msg":"everything is working!"
}
Run Code Online (Sandbox Code Playgroud)

JSON正在转换为NSDictionary.

NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization
                          JSONObjectWithData:data
                          options:NSJSONReadingMutableContainers
                          error: &error];
Run Code Online (Sandbox Code Playgroud)

我使用以下代码访问NSDictionary值.

int error_code = (int)[jsonDict valueForKey:@"error_code"]
NSLog(@"%i", error_code);
The log outputs the following: 143005344
Run Code Online (Sandbox Code Playgroud)

我甚至尝试过objectForKey并得到相同的响应.

提前致谢.

Lef*_*ris 54

是的它输出值的指针,这就是你看到这个日志输出的原因.

您不能将指针强制转换为整数并期望该值.

int error_code = [[jsonDict valueForKey:@"error_code"] integerValue];
Run Code Online (Sandbox Code Playgroud)

或者如果你想使用现代的目标-c

int error_code = [jsonDict[@"error_code"] integerValue];
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用`int`和`intValue`,或者`NSInteger`和`integerValue` - 但你不应该在没有显式强制转换的情况下混合它们. (5认同)

Mik*_*ler 9

数字作为NSNumber实例存储在plist/json词典中.试着NSNumberintValue以下人士一样打电话:

int error_code = [jsonDict[@"error_code"] intValue];
Run Code Online (Sandbox Code Playgroud)

另请注意字典的新下标语法.