ios – 如何从NSDictionary获取整数值?

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

来自服务器的JSON响应代码

{
"status":"ok","error_code":0,"data" : [],"msg":"everything is working!"
}

JSON正在转换为NSDictionary.

NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization
                          JSONObjectWithData:data
                          options:NSJSONReadingMutableContainers
                          error: &error];

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

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

我甚至尝试了objectForKey,并得到相同的回复.

提前致谢.

解决方法

是的,它输出值的指针,这就是为什么你看到这个日志输出.

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

int error_code = [[jsonDict valueForKey:@"error_code"] integerValue];

或者如果要使用现代目标c

int error_code = [jsonDict[@"error_code"] integerValue];

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...