Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add NSDecimalNumbers?

Tags:

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!

like image 379
Terry B Avatar asked Mar 15 '10 18:03

Terry B


1 Answers

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++!

like image 198
Frank Krueger Avatar answered Sep 21 '22 21:09

Frank Krueger