How to determine the true data type of an NSNumber?

前端 未结 4 1493
悲哀的现实
悲哀的现实 2020-12-02 00:22

Consider this code:

NSNumber* interchangeId = dict[@\"interchangeMarkerLogId\"];
long long llValue = [interchangeId longLongValue];
double dValue = [intercha         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-02 01:08

    Ok--It's not 100% ideal, but you add a little bit of code to SBJSON to achieve what you want.

    1. First, add NSNumber+SBJson to the SBJSON project:

    NSNumber+SBJson.h

    @interface NSNumber (SBJson)
    @property ( nonatomic ) BOOL isDouble ;
    @end
    

    NSNumber+SBJson.m

    #import "NSNumber+SBJSON.h"
    #import 
    
    @implementation NSNumber (SBJson)
    
    static const char * kIsDoubleKey = "kIsDoubleKey" ;
    
    -(void)setIsDouble:(BOOL)b
    {
        objc_setAssociatedObject( self, kIsDoubleKey, [ NSNumber numberWithBool:b ], OBJC_ASSOCIATION_RETAIN_NONATOMIC ) ;
    }
    
    -(BOOL)isDouble
    {
        return [ objc_getAssociatedObject( self, kIsDoubleKey ) boolValue ] ;
    }
    
    @end
    

    2. Now, find the line in SBJson4StreamParser.m where sbjson4_token_real is handled. Change the code as follows:

    case sbjson4_token_real: {
        NSNumber * number = @(strtod(token, NULL)) ;
        number.isDouble = YES ;
        [_delegate parserFoundNumber:number ];
        [_state parser:self shouldTransitionTo:tok];
        break;
    }

    note the bold line... this will mark a number created from a JSON real as a double.

    3. Finally, you can check the isDouble property on your number objects decoded via SBJSON

    HTH

    edit:

    (Of course you could generalize this and replace the added isDouble with a generic type indicator if you like)

提交回复
热议问题