From my understanding of NSNumber, if you create NSNumber with a certain data type, you need to access the variable with that same data type. For example
NSNumber *myIntNumber = [NSNumber numberWithInt:1];
int myInt = [myIntNumber intValue];
NSNumber *myNSIntegerNumber = [NSNumber numberWithInteger:1];
NSInteger myInteger = [myIntNumber integerValue];
If a NSNumber is created using a #define variable:
#define MY_DEFINE 6
does that mean that I cannot do the following
NSNumber *myNSIntegerNumber = [NSNumber numberWithInteger:MY_DEFINE];
NSInteger myInteger = [myIntNumber integerValue];
because MY_DEFINE is not a NSInteger?
I know that the above code would work in a 32-bit app, but I am trying to make sure that it will work on a 64-bit app, which is much more picky about these things, as well. And of course, it never hurts to do things properly.
If I cannot do the above, should I try to define MY_DEFINE differently so that I could use it to create a NSNumber that can later be used to retrieve a NSInteger?
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 .
It is not a C primitive (like int, unsigned int, float, double, etc.) NSInteger , CGFloat , NSUInteger are simple typedefs over the C primitives. The need for NSNumber arises from the need to use numbers as parameters to APIs that require Objects.
NSCFNumber is a concrete, "private" implementation of a class in that cluster.
Your understanding of NSNumber
is incorrect. You can create an NSNumber
with any type it supports and you can then use any of the supported type accessors. The two do not need to the same.
// Perfectly valid
NSNumber *number = [NSNumber numberWithFloat:3.14];
int val = [number intValue]; // results in 3
Your use of the #define
is perfectly valid. The pre-compiler simply translates your code to:
NSNumber *myNSIntegerNumber = [NSNumber numberWithInteger:6];
Remember, a #define
is nothing more than simple copy and paste (at least in this type of simple form) done before the code is compiled.
You can even use modern syntax:
NSNumber *number = @MY_DEFINE;
which becomes:
NSNumber *number = @6;
BTW - why post this question? Why not just try it first?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With