How do I increment a NSNumber?
i.e. myNSNumber++
If you're using it to store an integral value:
myNSNumber = @(myNSNumber.longLongValue + 1);
For floating point stuff the short answer is the following, but it's a bad idea to do this, you'll loose precision and if you're doing any kind of comparison later like [myNSNumber isEqual:@(4.5)] you might be surprised:
myNSNumber = @(myNSNumber.floatValue + 1);
If you need to do math on floating point numbers represented as objects in Objective-C (i.e. if you need to put them in arrays, dictionaries, etc.) you should use NSDecimalNumber
.
Use a category to ease future use. Here is a basic idea.
- (void)incrementIntBy:(int)ammount {
self = [NSNumber numberWithInt:(self.intValue + ammount)];
}
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];