1

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?

Bucky
  • 21
  • 2
  • Can you try `NSExpression *absExpression = [NSExpression expressionForFunction:@"abs:" arguments:@[keyPathExpression]]; NSExpression *expression = [NSExpression expressionForFunction:@"sum:" arguments:@[absExpression]];` ? – Martin R Aug 22 '13 at 11:26
  • Nope, sadly doesn't work. Get SIGABRT when executing the request with error: `Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Bad argument to aggregate total in select (must be a keypath or constant value) : ( "abs:(value)" )'` – Bucky Aug 22 '13 at 16:33
  • It was just a guess :-) But some NSExpression combinations just don't work, see for example http://stackoverflow.com/questions/14122086/chained-expressions-to-perform-calculations-in-core-data for a similar issue. Unfortunately, I do not have a better idea, but perhaps someone else comes up with one. – Martin R Aug 22 '13 at 17:22

0 Answers0