NSNumber and NSInteger
If you’ve ever found yourself scratching your head thinking “now which one should I be using, NSNumber or NSInteger?” the short summary below should help.
NSInteger is nothing more than a synonym for an integer. What follows is how NSInteger is defined:
1 2 3 4 5 6 7 | #if __LP64__ || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endif |
NSNumber is an Objective-C class, a subclass of NSValue to be specific. You can create an NSNumber object from a signed or unsigned char, short int, int, long int, long long int, float, double or BOOL.
One of the primary distinctions is that you can use NSNumber in collections, such as NSArray, where an object is required. For example, if you need to add a float into an NSArray, you would first need to create an NSNumber object from the float:
1 2 3 4 | float percentage = 40.5; ... // Create NSNumber object, which can now be inserted into an NSArray NSNumber *percentageObject = [NSNumber numberWithFloat:percentage]; |
NSInteger is a simply an integer, NSNumber is an object.









Hi there. I found this article useful, but have a further question. I converted an int into an NSNumber and was able to successfully save it to my preferences.plist for my application. I am a bit befuddled when it comes to reading the NSNumber back out and converting it into an int again. Yes, I am fairly new to objective C, and am not sure how to cast the NSNumber back into an int.
Chris,
It depends on how you stored the NSNumber to the plist. For example, if you stored the NSNumber object into an NSArray, you might have something like this:
NSInteger someInt = [[tmpArray objectAtIndex:0] integerValue];
In this case I am assuming the NSNumber object was stored in a plist which was an array of objects. I then convert the value at index 0 to an integer (using the method integerValue).
John
That worked like a charm. Thanks for the speedy answer!
Thanks for this post, cleared a (noob) problem I’ve been having with my NSDictionary.
How do I check on receipt of a variable if it is NSInteger or NSNumber?
-(void)reportDataType:number{
if(…) NSLog(@”received NSInteger”);
if(…) NSLog(@”received NSNumber”);
}
Justin,
I don’t think it’s possible to write a method as you have shown passing in a “number” as NSNumber is an object and NSInteger is standard C data type (not an object). You could have a method where you pass in an object of type “id” the generic object type and then determine if the object is an NSNumber similar to this:
I wrote about determining class types here: Determining Class Types
Hope that helps.