Reputation: 221
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!
Upvotes: 22
Views: 11194
Reputation: 747
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:
Upvotes: 10
Reputation: 70983
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++!
Upvotes: 22
Reputation: 25765
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.
Upvotes: 2
Reputation: 170829
See NSDecimalAdd
function (as well as NSDecimalMultiply, NSDecimalDivide, NSDecimalSubtract).
Upvotes: 6
Reputation: 122429
[[numOne decimalNumberByAdding:numTwo] decimalNumberByAdding:numThree]
Upvotes: 2