This question already has answers here:
Calculating a simple sum with Core Data
(3个答案)
5年前关闭。
我有带有实体(Deductions)的核心数据,它具有三个属性,第一个属性(deductionName),第二个属性是(deductionStatus),最后一个属性是(deductionAmount)。
现在如果(deductionStatus)== 1,我想获得(deductionAmount)的总和
(deductionStatus)是一个布尔值。
(3个答案)
5年前关闭。
我有带有实体(Deductions)的核心数据,它具有三个属性,第一个属性(deductionName),第二个属性是(deductionStatus),最后一个属性是(deductionAmount)。
现在如果(deductionStatus)== 1,我想获得(deductionAmount)的总和
(deductionStatus)是一个布尔值。
return [[[self.fetchedDeductionData fetchedObjects] valueForKeyPath:@"@sum.deductionAmount"]floatValue];
最佳答案
显而易见的解决方案是仅获取deductionAmount
并自己进行求和(因为我并不认为SQLite进行的求和与您进行的求和之间存在区别):
// build your NSFetchRequest
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"deductionStatus == 1"];
[request setPredicate:predicate];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch: [NSArray arrayWithObjects:@"deductionAmount", nil]];
// execute fetch request
// iterate through the array
CGFloat sum = 0;
for (NSDictionary *dictionary in fetchedResults) {
NSNumber *amount = [dictionary objectForKey:@"deductionAmount"];
sum = sum + [amount doubleValue]
}
关于ios - 如何获得核心数据的SUM ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24415215/
10-10 18:41