You have to create a NSFetchRequest
and use the setPropertiesToGroupBy
method.
To get the sum of an attribute you have to use a combination of NSExpression
and NSExpressionDescription
:
NSExpression *amountExpr = [NSExpression expressionForKeyPath:@"amount"];
NSExpression *totalAmountExpr = [NSExpression expressionForFunction:@"sum:" arguments:@[amountExpr]];
NSExpressionDescription *totalAmountExprDesc = [[NSExpressionDescription alloc] init];
[totalAmountExprDesc setName:@"totalAmount"];
[totalAmountExprDesc setExpression: totalAmountExpr];
[totalAmountExprDesc setExpressionResultType:NSDoubleAttributeType];
Further information about NSExpression
: Apple Docs NSExpression
When creating the NSFetchRequest
you have to make sure to set the result to be NSDictionaryResultType
and to add the totalAmountExprDesc
to the properties to fetch. Note that you also add the attribute that you want to group by to the properties to fetch.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:@[@"ownedAccount", totalAmountExprDesc, ...]];
[fetchRequest setPropertiesToGroupBy:@[@"ownedAccount"]];
Further information about NSFetchRequest
: Apple Docs NSFetchRequest
With that you have the basic fetch request to use for your query.