Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math with NSNumbers and ints

In objective-c I am trying to evaluate the following expression: _c = _f / 5 * 8; It tells me that an int and a NSNumber are invalid arguments to a binary expression.

Whats wrong? I am just getting started with objective-c and cocoa but am familiar with php and basic and kinda familiar with javascript.

like image 403
yskywalker Avatar asked Mar 27 '12 11:03

yskywalker


2 Answers

Objective-C has several different structures in place for you to use in calculations. From its C roots come the primitive numbers, ints, floats, doubles, etc, on which you can perform arithmetic operations directly (+, -, *, /, etc.). These are what you're looking to use.

On a higher lever, Objective-C also has NSNumber objects, which are simple wrappers for the primitive types listed above. They're used throughout Objective-C where primitives need to be stored (often within other objects such as arrays and dictionaries that don't take primitive values directly). Because NSNumbers are objects, you cannot perform direct arithmetic operations on them, you have to draw out their primitive values first (using intValue, for instance, to get an integer value, or doubleValue to get a double-precision floating point number). Because it's unclear what the variables represent in your question, I'm not going to venture a guess as to what it is you're trying to do (I don't want to mislead you), but you can find out more about NSNumber in the NSNumber Class Reference.

Finally, as Richard mentioned, there are NSDecimalNumbers. These are almost never used, since they're either simply not needed (they're designed to hold extremely high-precision numbers, far beyond the capacity of regular primitive values), or too complicated to use. They also have their own methods for performing arithmetic operations, and are generally irrelevant for everyday use. Again, if you're interested, look more into the NSDecimalNumber Class Reference.

For the most part, you're looking to use primitive numbers to do your calculations. When you need to store them, you can often 'box' and 'unbox' (store and retrieve) from NSNumber objects.

like image 97
Itai Ferber Avatar answered Nov 11 '22 23:11

Itai Ferber


You can't do these things with objects(NSNumber in this case). So you will have to take its' int/double/long/float value. I don't know which one is NSNumber, so here are 2 solutions, 1 will work:

_c = [_f doubleValue] / 5 * 8;

or:

_c = [NSNumber numberWithDouble:(_f / 5 * 8)];

Hope it helps

like image 20
Novarg Avatar answered Nov 11 '22 22:11

Novarg