How to increment a NSNumber

前端 未结 9 1241
情书的邮戳
情书的邮戳 2020-12-13 01:47

How do I increment a NSNumber?

i.e. myNSNumber++

相关标签:
9条回答
  • 2020-12-13 02:35

    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.

    0 讨论(0)
  • 2020-12-13 02:39

    Use a category to ease future use. Here is a basic idea.

     - (void)incrementIntBy:(int)ammount {
          self = [NSNumber numberWithInt:(self.intValue + ammount)];
     }
    
    0 讨论(0)
  • 2020-12-13 02:40

    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];
    
    0 讨论(0)
提交回复
热议问题