问题
Before putting int value into dictionary i have set the int value as [NSNumber numberWithInt:2], now when i try to retrieve back the dictionary content , i want it back in int format.. hw to do this??
here's my code;
NSMutabelDictionary *dict = [[NSMutableDictionary alloc]init];
int intValue = 300;
[dict setObject:[NSNumber numberWithInt:intValue] forKey:@"integer"];
retriving.........
int number = [dict ObjectForKey:@"integer"];
.. it throws an exception sayin casting is required.. when i do it this way..
int number = (int)[dict ObjectForKey:@"integer"];
stil it doesnt work...
how to solve this problem?/
please suggest..
回答1:
Have a look at the documentation. Use the intValue method:
int number = [[dict objectForKey:@"integer"] intValue];
回答2:
You should stick to the NSInteger data types when possible. So you'd create the number like that:
NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];
Decoding works with the integerValue method then:
NSInteger value = [number integerValue];
回答3:
Use the NSNumber method intValue
Here is Apple reference documentation
回答4:
A less verbose approach:
int number = [dict[@"integer"] intValue];
回答5:
A tested one-liner:
int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;
来源:https://stackoverflow.com/questions/3555906/how-to-convert-nsnumber-to-int-in-objective-c