TheLearner TheLearner - 1 year ago 142
Objective-C Question

How to increment a NSNumber

How do I increment a NSNumber?

i.e. myNSNumber++

Answer Source

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