How do I increment a NSNumber?
i.e. myNSNumber++
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];
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);
I like the dot expression because it is more concise and that is why IOS supports it in the first place:
myNSNumber = [NSNumber numberWithInt:myNSNumber.intValue + 1];
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.
Lots of good info in the answers to this question. I used the selected answer in my code and it worked. Then I started reading the rest of the posts and simplified the code a lot. It’s a bit harder to read if you aren’t familiar with the changes in notation that were introduced in Xcode 5, but it’s a lot cleaner. I probably could make it just one line, but then it’s a little too hard to figure out what I’m doing.
I’m storing an NSNumber in a dictionary and I want to increment it. I get it, convert it to an int, increment it while converting it to an NSNumber, then put it back into the dictionary.
Old Code
NSNumber *correct = [scoringDictionary objectForKey:@"correct"];
int correctValue = [correct intValue];
correct = [NSNumber numberWithInt:correctValue + 1];
[scoringDictionary removeObjectForKey:@"correct"];
scoringDictionary[@"correct"] = correct;
New code
NSNumber *correct = [scoringDictionary objectForKey:@"correct"];
scoringDictionary[@"correct"] = @(correct.intValue + 1);
Put them all together, and you have:
myNSNumber = @(myNSNumber.intValue + 1);