NSNumber is a wrapper class over any general integral type. In order to do arithmetic you must get the primitive type of data that you want to do arithmetic with, and then do the arithmetic and then wrap it up again in an NSNumber
.
An example of multiplying a number by 5
and adding 4
is below:
NSNumber *num = // get this somewhere
num = @(num.intValue * 5 + 4);
In theory one can create a subclass with methods of -addInt
and the such, but I personally use macros like follow:
#define NSNumberAddInt(num, i) num = @( num.intValue + i )
#define NSNumberMultiplyInt(num, i) num = @( num.intValue * i )
#define NSNumberMultiplyAddInt(num, i, j) num = @(num.intValue * i + j)
In reality I have some more complex macros that actually declare inline functions:
#define NSNumberDeclareAddType(type, utype) \\
inline NSNumber *NSNumberAdd ## utype ( NSNumber *inNum, type i ) {
return @( inNum. type ## Value + i );
}
#define NSNumberDeclareMultiplyType(type, utype) \\
inline NSNumber *NSNumberMultiply ## utype ( NSNumber *inNum, type i ) {
return @( inNum. type ## Value * i );
}
#define NSNumberDeclareMultiplyAddType(type, utype) \\
inline NSNumber *NSNumberMultiplyAdd ## utype ( NSNumber *inNum, type i, type j ) {
return @( inNum. type ## Value * i + j );
}
#define NSNumberDecalreArithmeticType(type, utype) NSNumberDeclareAddType(type, utype) \\
NSNumberDeclareMultiplyType(type, utype) \\
NSNumberDeclareMultiplyAddType(type, utype)
And then adding lines like
NSNumberDecalreArithmeticType(int, Int)
NSNumberDecalreArithmeticType(float, Float)
NSNumberDecalreArithmeticType(double, Double)
Of course, in theory this can be simplified with c++ templates, but I'm no c++ guru (then again I'm no guru in general) so I don't want to post any c++ code.