If you are new to Objective-C like me you may see this error quite a bit -
<pre><code class=language-objectivec> Invalid operands to binary expression ('NSInteger' (aka 'long') and 'NSNumber *') </code></pre>
It means that you aren't using the correct datatype. No worries though we'll get that cleared up right now.
NSNumber
A NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char, short int, int, long int, long long int, float, or double or as a BOOL. (Note that number objects do not necessarily preserve the type they are created with.) It also defines a compare: method to determine the ordering of two NSNumber objects.
That is a whole lot mumbo jumbo that might not be totally clear to you yet. Here is what you need to know --
- NSNumbers are an object datatype so you will use *pointers with them.
- If you are going to be doing any math on the numeric value don't use NSNumber
- NSNumber objects can added to a collection like an array or dictionary
- You can also skip conversions by wrapping your NSNumber object with @() to do math
double x = 4.0; NSNumber *result = @(x * .10); NSLog(@"%.2f", [result doubleValue]);
NSInteger
NSIntegers are not an object. Instead they are a wrapper for the long (signed and unsigned) integer primitive datatype. One of the reasons Apple added NSInteger to Objective-C was so make your life easier dealing with 32 and 64 bit systems. No matter what architecture you are building NSInteger will use the correct type.
- You do not use *pointers when declaring NSIntegers
- NSInteger allows math operations
- When printing a NSInteger you'll need to use the %ld format specifier
- Cannot be added to a collection. A conversion to NSNumber is necessary
Conversion Examples
NSNumber -> NSInteger
NSInteger myInteger = [myNumber integerValue];
NSInteger -> NSNumber
NSNumber *myNumber = [NSNumber numberWithInteger:myInteger];
Now that it is all clear we won't be seeing any more warnings about