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"];
Have a look at the documentation. Use the intValue
method:
NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];