6
votes

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?

1

1 Answers

10
votes

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?