简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM