如何对数组的货币项进行求和

时间:2014-04-27 10:10:29

标签: ios sum nsnumber nsnumberformatter

我想要对数组的项进行求和。这些物品是货币。但是,从String解析NSNumber时会出现问题。请参阅下面的代码

NSString *cash;
cash = self.textfield.text; // textfield has format: currencyFormatter

NSNumberFormatter * number = [[NSNumberFormatter alloc] init]; 
[number setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber * myNumber = [number numberFromString:cash]; // convert into number from string
NSLog(@"myNumber:%@",myNumber);

NSMutableArray *tmp_cash;
[tmp_cash addObject:myNumber]; // add object to Array
long long sum = ((NSNumber*)[tmp_cash valueForKeyPath:  @"@sum.longLongValue"]).longLongValue; // sum items of array

但是,应用崩溃并显示日志myNumbernull。请帮我解决这个错误

1 个答案:

答案 0 :(得分:0)

使用您用于显示currencyFormatter中的号码的textField。将currencyFormatter更改为属性,然后懒洋洋地加载它,以确保它始终初始化:

@property (nonatomic, strong) NSNumberFormatter *currencyFormatter;

-(NSNumberFormatter *)currencyFormatter
{
    if (!_currencyFormatter) {
        _currencyFormatter = [NSNumberFormatter new];
        // set up other options
    }
    return _currencyFormatter;
}

现在您可以使用它来解析UITextField

中的文本
NSString *cash;
cash = self.textfield.text; // textfield has format: currencyFormatter

NSNumber * myNumber = [self.currencyFormatter numberFromString:cash]; // convert into number from string
NSLog(@"myNumber:%@",myNumber);