Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an integer value from NSDictionary?

I am having this weird issue. NSDictionary is not returning the correct integer value.

JSON response code from server.

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

The JSON is being converted to a NSDictionary.

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

I access the NSDictionary value using the following code.

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

I've even tried objectForKey and I get the same response.

Thanks, in advance.

like image 727
James Avatar asked Sep 04 '13 12:09

James


2 Answers

Yes it outputs the pointer of the value and that's why you see this log output.

You cannot cast the pointer to an integer and expect the value.

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

or if you want to use modern objective-c

int error_code = [jsonDict[@"error_code"] integerValue];
like image 140
Lefteris Avatar answered Nov 01 '22 10:11

Lefteris


Numbers are stored as NSNumber instances in plist/json dictionaries. Try calling one of NSNumber's getters like intValue:

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

Note also the new subscripting syntax for dictionaries.

like image 43
Mike Weller Avatar answered Nov 01 '22 10:11

Mike Weller