Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiplication and addition with NSNumber

I want to implement simple calculation with NSNumber.

For ex:

int a;
a=a*10;
a=a+1;
NSLog(@"%d",a);

How to do the same thing if i declare

NSNumber *a;

I want to implement the same logic with NSNumber which I implemented using integer. Thanks

like image 891
user3575678 Avatar asked May 29 '14 06:05

user3575678


1 Answers

There is no explicit support for doing math operations on NSNumber. NSNumber is used to wrap a primitive type number. (e.g. use it for storing in arrays/dicitionaries)

If you have an NSNumber instance and you want to make math operations you should extract its value into a primitive type :

int num = [numberInstance intValue]; 
num += 1; // Just for the example;

After you are done create a new instance for storing the new value (since NSNumber is immutable you cannot use the old NSNumber instance)

numberInstance = [NSNumber numberWithInt:num];
like image 179
giorashc Avatar answered Sep 19 '22 05:09

giorashc