get type of NSNumber

后端 未结 12 602
鱼传尺愫
鱼传尺愫 2020-11-29 02:33

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] initWithB         


        
12条回答
  •  被撕碎了的回忆
    2020-11-29 02:46

    objCType documentation states that The returned type does not necessarily match the method the number object was created with

    Secondly, other methods of comparing the class of number to a given class type or assuming boolean number instances to be shared singletons are not documented behaviour.

    A more(not completely though) reliable way is to depend on NSJSONSerialisation as it correctly recognises number instances created with bool and outputs true/false in json. This is something we can expect Apple to take care of while moving with new SDKs and on different architectures. Below is the code:

    +(BOOL) isBoolType:(NSNumber*) number {
    
        NSError* err;
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"key":number}
                                                           options:0
                                                             error:&err];
    
        NSString* jsonString = [[NSString alloc] 
                                  initWithData:jsonData
                                      encoding:NSUTF8StringEncoding];
    
        return [jsonString containsString:@"true"]
                || [jsonString containsString:@"false"];
    
    }
    

提交回复
热议问题