ok404
ok404

Reputation: 352

NSInteger not equal to long?

I am trying to parse some json data in Cocoa and I am having troubles with the NSInteger data type. The json string has some long values that I assign to NSInteger properties. Unfortunately the assigned NSInteger value differs completely from the long value. Why is that so? NSInteger is defined as typedef long NSInteger. I could have assigned the long value to a long property but I just would like to know why I can't assign it to an NSInteger.

    -(void)parseData:(NSData*)data
{
    NSError*err=nil;
    NSDictionary*jsonData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
    _userID=(NSInteger)[jsonData valueForKeyWithoutNSNull:@"id"];
}

The _userID is a NSInteger. The value retrieved from the dictionary is a long.

Upvotes: 0

Views: 443

Answers (1)

rmaddy
rmaddy

Reputation: 318854

You can't simply cast an NSNumber (or even NSString) to an NSInteger. Dictionaries and other collection classes can't store primitive types like NSInteger.

Assuming your dictionary contains numbers and not strings then you need:

NSNumber *number = [jsonData valueForKeyWithoutNSNull:@"id"];
_userID = [number integerValue];

Upvotes: 2

Related Questions