[objective-c] 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"];

This question is related to objective-c nsnumber

The answer is


Use the NSNumber method intValue

Here is Apple reference documentation


A less verbose approach:

int number = [dict[@"integer"] intValue];

A tested one-liner:

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

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