NSNumber vs NSInteger

The notion of NSInteger and NSNumber may seem confusing at first glance, but in reality it is simple.
NSNumber is a subclass of NSValue – container for C or Objective-C data item. The purpose of NSValue class, and, hence, NSNumber class – to allow items of different data types (ints, floats, chars, pointers, structures, as well as object ids) to be added to collections, such as instances of NSArray, for example. As simple is that!

With that purpose in mind, it’s easy to memorize NSNumber features:
1. it stores and retrieve primitives, but it’s NOT primitive;
2. it can be displayed using %@ format specifier;
3. it is incredible useful when we need to stick a number into NSArray of NSDictionary.

NSInteger also has some features:
1. it is very much like traditional int in C, only it save us from dealing with int/long on 32/64 bit processor architecture;
2. it is a primitive.

We can convert them between each other:

NSInteger myInt = [numberValue integerValue]; //NSNumber to NSInteger
//NSInteger to NSNumber
NSNumber myNum = [NSNumber numberWithInteger: integerValue]; 
NSNumber myNum = @(integer);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s