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];

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...