Convert NSNumber to int in Objective-C
I use [NSNumber numberWithInt:42]
or @(42)
to convert an int to NSNumber before adding it to an NSDictionary:
int intValue = 42;
NSNumber *numberValue = [NSNumber numberWithInt:intValue];
NSDictionary *dict = @{ @"integer" : numberValue };
When I retrieve the value from the NSDictionary, how can I transform it from NSNumber back to int?
NSNumber *number = dict[@"integer"];
int *intNumber = // ...?
It throws an exception saying casting is required when I do it this way:
int number = (int)dict[@"integer"];
Solution 1:
Have a look at the documentation. Use the intValue
method:
NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];
Solution 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];
Solution 3:
Use the NSNumber method intValue
Here is Apple reference documentation