Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get type of NSNumber

I want to get the type of NSNumber instance.

I found out on http://www.cocoadev.com/index.pl?NSNumber this:

  NSNumber *myNum = [[NSNumber alloc] initWithBool:TRUE];   if ([[myNum className] isEqualToString:@"NSCFNumber"]) {   // process NSNumber as integer  } else if  ([[myNum className] isEqualToString:@"NSCFBoolean"]) {   // process NSNumber as boolean  } 

Ok, but this doesn't work, the [myNum className] isn't recognized by the compiler. I'm compiling for iPhone.

like image 664
okami Avatar asked Mar 25 '10 19:03

okami


People also ask

What is NSNumber?

Overview. 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 .

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


2 Answers

I recommend using the -[NSNumber objCType] method.

It allows you to do:

NSNumber * n = [NSNumber numberWithBool:YES]; if (strcmp([n objCType], @encode(BOOL)) == 0) {     NSLog(@"this is a bool"); } else if (strcmp([n objCType], @encode(int)) == 0) {     NSLog(@"this is an int"); } 

For more information on type encodings, check out the Objective-C Runtime Reference.

like image 107
Dave DeLong Avatar answered Oct 18 '22 05:10

Dave DeLong


You can get the type this way, no string comparisons needed:

CFNumberType numberType = CFNumberGetType((CFNumberRef)someNSNumber); 

numberType will then be one of:

enum CFNumberType {    kCFNumberSInt8Type = 1,    kCFNumberSInt16Type = 2,    kCFNumberSInt32Type = 3,    kCFNumberSInt64Type = 4,    kCFNumberFloat32Type = 5,    kCFNumberFloat64Type = 6,    kCFNumberCharType = 7,    kCFNumberShortType = 8,    kCFNumberIntType = 9,    kCFNumberLongType = 10,    kCFNumberLongLongType = 11,    kCFNumberFloatType = 12,    kCFNumberDoubleType = 13,    kCFNumberCFIndexType = 14,    kCFNumberNSIntegerType = 15,    kCFNumberCGFloatType = 16,    kCFNumberMaxType = 16 }; typedef enum CFNumberType CFNumberType; 
like image 45
Chris Avatar answered Oct 18 '22 05:10

Chris