我想要对数组的项进行求和。这些物品是货币。但是,从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
但是,应用崩溃并显示日志myNumber
为null
。请帮我解决这个错误
答案 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);