views:

2691

answers:

1

Now this must be easy, but how can sum two NSNumber? Is like:

[one floatValue] + [two floatValue]

or exist a better way?

+10  A: 

There is not really a better way, but you really should not be doing this if you can avoid it. NSNumber exists as a wrapper to scalar numbers so you can store them in collections and pass them polymorphically with other NSObjects. They are not really used to store numbers in actual math. If you do math on them it is much slower than performing the operation on just the scalars, which is probably why there are no convenience methods for it.

For example:

NSNumber *sum = [NSNumber numberWithFloatValue:([one floatValue] + [two floatValue])];

Is blowing at a minimum 21 instructions on message dispatches, and however much code the methods take to unbox the and rebox the values (probably a few hundred) to do 1 instruction worth of math.

So if you need to store numbers in dicts use an NSNumber, if you need to pass something that might be a number or string into a function use an NSNumber, but if you just want to do math stick with scalar C types.

Louis Gerbarg
I'd add that if you need to store collections of numbers for which you intend to do a lot of math - perhaps you really want a C style array of the proper numeric type?
Kendall Helmstetter Gelner
Whenever you are doing a lot of math you want to use the scalars, you want to use the objects when you need polymorphism or they need to fit in existing containers.
Louis Gerbarg