如何获得正确的值和类型的NSNumber?

时间:2019-04-07 08:41:36

标签: objective-c nsnumber

我正在通过使用NSNumber检查字符串是float还是int来从字符串创建NSNumberFormatter。我想要一种方法来返回NSNumber的类型和正确的值。它适用于int,但不适用于十进制数字。

NSNumber *n;
enum CFNumberType _numberType;

- (instancetype)initWithString:(NSString *)string {
    self = [super init];
    if (self) {
        NSNumberFormatter *formatter = [NSNumberFormatter new];
        decimalPattern = @"\\d+(\\.\\d+)";
        if ([Utils matchString:string withPattern:decimalPattern]) {
            // Float
            formatter.numberStyle = NSNumberFormatterDecimalStyle;
            _numberType = kCFNumberDoubleType;
            n = [formatter numberFromString:string];
        } else {
            // Integer
            formatter.numberStyle = NSNumberFormatterNoStyle;
            _numberType = kCFNumberIntType;
            n = [formatter numberFromString:string];
        }
        self = [self initWithNumber:n];
    }
    return self;
}


- (CFNumberType)value {
    CFNumberType num;  // How to determine the type of num? 
    CFNumberGetValue((CFNumberRef)n, _numberType, &num);
    return num;
}

- (CFNumberType)numberType {
    return _numberType;
}

value方法中,如果我指定float num,则它适用于浮点数。但是我不能使用float,因为我也想使它适用于int。该怎么做?

1 个答案:

答案 0 :(得分:0)

我已经找到了解决方案。首先检查数字是否为double,然后调用适当的value方法。

- (BOOL)isDouble {
    if (_numberType == kCFNumberFloatType || _numberType == kCFNumberFloat32Type || _numberType == kCFNumberFloat64Type || _numberType == kCFNumberDoubleType) {
        return YES;
    }
    return NO;
}

- (double)doubleValue {
    if ([self isDouble]) {
        return [n doubleValue];
    }
    return 0.0;
}

- (int)intValue {
    if (![self isDouble]) {
        return [n intValue];
    }
    return 0;
}