Convert NSNumber to int in Objective-C

suse picture suse · Aug 24, 2010 · Viewed 159k times · Source

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

Answer

Felix Kling picture Felix Kling · Aug 24, 2010

Have a look at the documentation. Use the intValue method:

NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];