How to increment a NSNumber

NSNumbers are immutable, you have to create a new instance.

// Work with 64 bit to support very large values
myNSNumber = [NSNumber numberWithLongLong:[myNSNumber longLongValue] + 1];

// EDIT: With modern syntax:
myNSNumber = @([myNSNumber longLongValue] + 1);

Update: FYI, I personally like BoltClock's and DarkDusts's one-line answers better. They're more concise, and don't require additional variables.


In order to increment an NSNumber, you're going to have to get its value, increment that, and store it in a new NSNumber.

For instance, for an NSNumber holding an integer:

NSNumber *number = [NSNumber numberWithInt:...];
int value = [number intValue];
number = [NSNumber numberWithInt:value + 1];

Or for an NSNumber holding a floating-point number:

NSNumber *number = [NSNumber numberWithDouble:...];
double value = [number doubleValue];
number = [NSNumber numberWithDouble:value + 1.0];

For anyone who is using the latest version of Xcode (writing this as of 4.4.1, SDK 5.1), with the use of object literals, you can clean the code up even a little bit more...

NSNumber *x = @(1);
x = @([x intValue] + 1);
// x = 2

Still kind of a pain to deal with the boxing and unboxing everything to do simple operations, but it's getting better, or at least shorter.


NSNumber objects are immutable; the best you can do is to grab the primitive value, increment it then wrap the result in its own NSNumber object:

NSNumber *bNumber = [NSNumber numberWithInt:[aNumber intValue] + 1];

Tags:

Objective C