带SUM的NSFetchedResultsController

时间:2013-03-05 03:24:46

标签: ios core-data nsfetchedresultscontroller

我应该如何通过第一个属性获取数据并将第二个属性的值相加?

通过简单的提取,我有:

enter image description here

但我需要在1行中显示相同的 ZINGREDIENT ,并将 ZCOUNT 的值相加:

enter image description here

就像:

select ZINGREDIENT, sum(ZCOUNT) 
from Table
group by ZINGREDIENT

1 个答案:

答案 0 :(得分:2)

这是非常简单的NSFetchRequest版本:

    NSManagedObjectContext* context = [object managedObjectContext];
    NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Join"];
    [request setResultType:NSDictionaryResultType];
    [request setReturnsDistinctResults:YES];
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"count"];
    NSExpression* expr = [NSExpression expressionForFunction:@"sum:" arguments:@[keyPathExpression]];
    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
    [expressionDescription setName:@"count"];
    [expressionDescription setExpression:expr];
    [expressionDescription setExpressionResultType:NSInteger32AttributeType];
    [request setPropertiesToGroupBy:@[@"ingredient"]];
    [request setPropertiesToFetch:@[@"ingredient",expressionDescription]];
    NSError* error = nil;
    NSArray* rez = [context executeFetchRequest:request error:&error];