How do I add NSDecimalNumbers?

2019-04-18 13:14发布

OK this may be the dumb question of the day, but supposing I have a class with :

NSDecimalNumber *numOne   = [NSDecimalNumber numberWithFloat:1.0];
NSDecimalNumber *numTwo   = [NSDecimalNumber numberWithFloat:2.0];
NSDecimalNumber *numThree = [NSDecimalNumber numberWithFloat:3.0];

Why can't I have a function that adds those numbers:

- (NSDecimalNumber *)addThem {
    return (self.numOne + self.numTwo + self.numThree);
}

I apologize in advance for being an idiot, and thanks!

5条回答
Lonely孤独者°
2楼-- · 2019-04-18 13:34

You can:

- (NSDecimalNumber *)addThem {
    return [[self.numOne decimalNumberByAdding:numTwo] decimalNumberByAdding:numThree];
}

The problem with your example is that what self.numOne really is at a bit level is a pointer to an object. So your function would return some random memory location, not the sum.

If Objective-C supported C++-style operator overloading, someone could define + when applied to two NSDecimalNumber objects as an alias to decimalNumberByAdding:. But it doesn't.

查看更多
老娘就宠你
3楼-- · 2019-04-18 13:42
[[numOne decimalNumberByAdding:numTwo] decimalNumberByAdding:numThree]
查看更多
Deceive 欺骗
4楼-- · 2019-04-18 13:44

You can't do what you want becuase neither C nor Objective C have operator overloading. Instead you have to write:

- (NSDecimalNumber *)addThem {
    return [self.numOne decimalNumberByAdding:
        [self.numTwo decimalNumberByAdding:self.numThree]];
}

If you're willing to play dirty with Objective-C++ (rename your source to .mm), then you could write:

NSDecimalNumber *operator + (NSDecimalNumber *a, NSDecimalNumber *b) {
    return [a decimalNumberByAdding:b];
}

Now you can write:

- (NSDecimalNumber *)addThem {
    return self.numOne + self.numTwo + self.numThree;
}

Go C++!

查看更多
虎瘦雄心在
5楼-- · 2019-04-18 13:46

NSDecimalNumber is an Objective C class which, when instantiated, produces an object which contains a number. You access the object (and objects in general) through methods only. Objective C doesn't have a way to directly express arithmetic against objects, so you need to make one of three calls:

  • -[NSDecimalNumber doubleValue], which extracts the numbers from your objects before adding the numbers. link
  • -[NSDecimalNumber decimalNumberByAdding], which creates an additional object, which may be more than you want. link
  • NSDecimalAdd, which, again, creates an additional object, which may be more than you want. link
查看更多
看我几分像从前
6楼-- · 2019-04-18 13:52

See NSDecimalAdd function (as well as NSDecimalMultiply, NSDecimalDivide, NSDecimalSubtract).

查看更多
登录 后发表回答