Reputation: 10563
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"];
Upvotes: 132
Views: 173236
Reputation: 782
A less verbose approach:
int number = [dict[@"integer"] intValue];
Upvotes: 1
Reputation: 817208
Have a look at the documentation. Use the intValue
method:
NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];
Upvotes: 207
Reputation: 6177
A tested one-liner:
int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;
Upvotes: 0
Reputation: 9364
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];
Upvotes: 62
Reputation: 5676
Use the NSNumber method intValue
Here is Apple reference documentation
Upvotes: 3