NSNumber type at runtime

Guides | Tutorial By 6 years ago

In Objective-C most things that get passed around inherit from NSObject. Because of this when you want to add a primative type to an array or dictionary you need to wrap it in an NSObject, usually an NSNumber. If you have specifically set an NSNumber“s value/type you can easily just use intValue, floatValue etc etc to pull out which ever type you put back in, but how do you know which type should be pulled out if your code is dynamic and uses any type of manosdeayuda.org courier;”>NSNumber.

The solution is within the [num objCType]; method. This will return a character array, the characters showing what the NSLog/printf representation of the value is. So for example an NSNumber of an int would have an objCType of “i”, an NSNumber of a float would have an objCType of “f” and etc etc.

You can get this character array directly from a datatype using @encode.

Now all that”s left to do is compare the two to determine what datatype you are working with:

NSNumber* num = nil;

if(strcmp([num objCType], @encode(BOOL)) == 0)
	[num boolValue];
else if(strcmp([num objCType], @encode(int)) == 0)
	[num intValue];
else if(strcmp([num objCType], @encode(unsigned int)) == 0)
	[num unsignedIntValue];
else if(strcmp([num objCType], @encode(long)) == 0)
	[num longValue];
else if(strcmp([num objCType], @encode(float)) == 0)
	[num floatValue];
else if(strcmp([num objCType], @encode(double)) == 0)
	[num doubleValue];
//	etc, etc