2014-06-25 18 views
0

我有核心数据与实体(扣除)它有三个属性第一个(deductionName)第二个(扣除状态),最后一个是(扣除额)。现在我如何在核心数据中获得SUM

我想获得的(deductionAmount)的总和,如果(deductionStatus)== 1

(deductionStatus)是一个布尔值。

return [[[self.fetchedDeductionData fetchedObjects] valueForKeyPath:@"@sum.deductionAmount"]floatValue]; 

回答

1

显而易见的解决方案是只取了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] 
} 
+0

' NSInteger x = [[self.fetchedDeductionData fetchedObjects] count]; float sum = 0;对于(int y = 0; y NamshanNet

+1

如果您不需要索引,for-in循环更快,则不要使用count和old for-loop遍历数组。 –