45

Is it possible to cast a NSInteger to a NSNumber object?

I need to convert the tag of a UIImageView object to a NSNumber object because I need to pass it as an argument to a function.

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Fitzy
  • 1,871
  • 6
  • 23
  • 40
  • It's absolutely possible to cast an NSInteger to an NSNumber*. The result will most likely lead to a crash. Of course if you have a number x, you can use @(x) to create an NSNumber object with the value x. Which will work, but is not a cast. – gnasher729 May 11 '14 at 21:26

3 Answers3

114

You cannot cast it because NSInteger is not an object, just an alias for a built-in type. You can always create a new NSNumber object from NSInteger, like this:

NSNumber *myNum = @(myNsIntValue);

or in the prior version of the compiler, use

NSNumber *myNum = [NSNumber numberWithInteger:myNsIntValue];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
19

since Apple LLVM Compiler 4.0, there is an easier way to create NSNumber object:

NSNumber *x = @1234; 
NSNumber *y = @(anIntegerVariable);
Brian
  • 30,156
  • 15
  • 86
  • 87
8

This is the more correct answer and it will not produce unexpected error.

NSNumber *myNum = [NSNumber numberWithInteger:myNsIntValue];

Because the doc said:

"numberWithInteger: Creates and returns an NSNumber object containing a given value, treating it as an NSInteger."

"numberWithInt: Creates and returns an NSNumber object containing a given value, treating it as a signed int."

Kevin
  • 828
  • 11
  • 14