IOS / Objective C / Core Data:对查询中属性的所有值求和

时间:2017-10-29 01:02:20

标签: ios core-data fetch

我想在核心数据提取后添加某个属性的所有值。是否有一些快捷方式,如总和会迅速返回。

这是我获取的标准代码。寻找能够使订单价值达到总和以获得所有订单总和的东西

- (id) getSalesTotal{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Orders"];
    fetchRequest.resultType = NSDictionaryResultType;

    NSError *error      = nil;
    self.managedObjectContext = [IDModel sharedInstance].managedObjectContext;

    NSArray *results    = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                                   error:&error];
    NSLog(@"error is %@",error);
    // NSLog(@"context%@",results);
    NSLog(@"beforevalueforkey%@",results);
    NSMutableArray * ordertotal = [[results valueForKey:@"orderprice"] mutableCopy];
    return ordertotal;//Is there something like sum(ordertotal)?????
}

1 个答案:

答案 0 :(得分:1)

您可以使用键值编码:

NSNumber *orderTotal = [arrayWhoseSumIsToBeCalculated valueForKeyPath:@"@sum.self"];