Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I figure out if the NSNumber I get back from -valueForKey: was initially an int or float?

The reason is I must get back the exact value as it was in the property. So if it was a float, I want to call -floatValue. But if it was an int, I want to call -intValue.

Is NSNumber remembering how it was initialized?

like image 679
Proud Member Avatar asked Apr 24 '11 13:04

Proud Member


1 Answers

NSNumber is toll-free bridged with CFNumber (see, amongst other sources, the text at the top of the CFNumber reference). So you can use CFNumberGetType. E.g.

- (void)logTypeOf:(NSNumber *)number
{
    switch(CFNumberGetType((CFNumberRef)number))
    {
        case kCFNumberSInt8Type:    NSLog(@"8bit signed integer"); break;
        case kCFNumberSInt16Type:   NSLog(@"16bit signed integer"); break;
        case kCFNumberSInt32Type:   NSLog(@"32bit signed integer"); break;

        /* ... etc, for all of:
           kCFNumberSInt64Type
           kCFNumberFloat32Type
           kCFNumberFloat64Type
           kCFNumberCharType
           kCFNumberShortType
           kCFNumberIntType
           kCFNumberLongType
           kCFNumberLongLongType
           kCFNumberFloatType
           kCFNumberDoubleType
           kCFNumberCFIndexType
           kCFNumberNSIntegerType
           kCFNumberCGFloatType
        */
   }
}

EDIT: looking more thoroughly at the documentation, CFNumberIsFloatType would appear to do exactly what you want without the complexity. So:

if(CFNumberIsFloatType((CFNumberRef)number))
{
    NSLog(@"this was a float");
}
else
{
    NSLog(@"this was an int");
}
like image 186
Tommy Avatar answered Sep 29 '22 00:09

Tommy