gpt4 book ai didi

ios - 解析 IOS for loop sum total

转载 作者:行者123 更新时间:2023-11-29 02:42:16 24 4
gpt4 key购买 nike

我正在尝试运行一个 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);
}


}];

最佳答案

您必须将 NSNumber 转换为基本类型(例如 floatint)才能执行算术运算

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);
}

关于ios - 解析 IOS for loop sum total,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25615556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com