我正在尝试运行for循环并添加解析数据库中的所有对象以提供总计。这是我一直得到的错误:二进制表达式的操作数无效('NSNumber *'和'NSNumber *')
这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
PFQuery *query = [PFQuery queryWithClassName:@"Account"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
NSNumber *sum;
for (PFObject *object in objects) {
NSString *balanceString = object[@"startingBalance"];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *balanceNumber = [f numberFromString:balanceString];
sum = sum + balanceNumber;
NSLog(@"%f", sum);
}
}];
答案 0 :(得分:1)
您必须将NSNumber
转换为基本类型(例如float
或int
)才能执行算术运算
float sum = 0;
NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; // and you should reuse formatter
[f setNumberStyle:NSNumberFormatterDecimalStyle];
for (PFObject *object in objects) {
NSString *balanceString = object[@"startingBalance"];
NSNumber *balanceNumber = [f numberFromString:balanceString];
sum += [balanceNumber floatValue];
NSLog(@"%f", sum);
}
答案 1 :(得分:0)
您不应对两个 nsnumber 对象执行算术运算,您应该将这些对象转换为float,long,double。执行算术运算后,您可以转换为 nsnumber 类型。