I'm currently using NSExpressions to process data I am retrieving from Core Data. The entities are of type 'Transaction' and have two attributes that I am interested in: type (NSString*
) and value (double
). What I would like is the sum of all absolute values for each type.
What I currently have is this:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Transaction" inManagedObjectContext:appDelegate.managedObjectContext];
NSAttributeDescription *att = [entity.attributesByName objectForKey:@"type"];
[request setEntity:entity];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"value"];
NSExpression *expression = [NSExpression expressionForFunction:@"sum:" arguments:@[keyPathExpression]];
NSExpressionDescription *expDesc = [[NSExpressionDescription alloc] init];
[expDesc setName:@"typeSum"];
[expDesc setExpression:expression];
[expDesc setExpressionResultType:NSDoubleAttributeType];
[request setPropertiesToFetch:@[expDesc, att]];
[request setPropertiesToGroupBy:@[att]];
[request setResultType:NSDictionaryResultType];
NSError *err = nil;
NSArray* results = [appDelegate.managedObjectContext executeFetchRequest:request error:&err];
This returns an NSArray filled with dictionaries that contain the type and the sum of values for entities with that type as shown below:
<_PFArray 0x15ecc5a0>(
{
type = TypeName1;
typeSum = "-15.5";
},
{
type = TypeName2;
typeSum = "22.5";
},
{
type = TypeName3;
typeSum = "237.9";
}
)
The issue with this is that the sum is not the sum of the absolute values. Is there a way that I can combine abs:
and sum:
to give me the result I want?