Things like max, min, and avg can be calculated just fine,
NSExpression *maxDate = [NSExpression expressionForKeyPath:@"startDate"];
NSExpression *maxDateExpression = [NSExpression expressionForFunction:@"max:"
arguments:@[maxDate]];
NSExpressionDescription *maxDateExpressionDescription = [[NSExpressionDescription alloc] init];
[maxDateExpressionDescription setName:@"maxDate"];
[maxDateExpressionDescription setExpression:maxDateExpression];
[maxDateExpressionDescription setExpressionResultType:NSDateAttributeType];
[request setPropertiesToFetch:@[maxDateExpressionDescription]];
// Execute the fetch.
NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (error) {
// Handle the error.
NSLog(@"Error!");
}
else {
NSLog(@"Max date is: %@", [objects[0] objectForKey:@"maxDate"]);
]
But, given I have "Item" entities, with the price I bought it for and the price I sold it for as attributes, how I calculate the total Profit of all Item entities using NSExpressions?
Thank you
The following expression description computes the price difference for each object:
NSExpression *price1Expr = [NSExpression expressionForKeyPath:@"price1"];
NSExpression *price2Expr = [NSExpression expressionForKeyPath:@"price2"];
NSExpression *profitExpr = [NSExpression
expressionForFunction:@"from:subtract:"
arguments:@[price2Expr, price1Expr]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"profit"];
[expressionDescription setExpression:profitExpr];
[expressionDescription setExpressionResultType:NSDoubleAttributeType];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
[request setPropertiesToFetch:@[expressionDescription]];
[request setResultType:NSDictionaryResultType];
NSArray *profits = [context executeFetchRequest:request error:&error];
NSLog(@"%@", profits);
EDIT: (The question was edited while I was writing the above answer.) Computing the sum of all price differences seems not to be possible with a single fetch request, see for example Chained expressions to perform calculations in Core Data. But you can fetch the array of all price differences, using the above expression description, and calculate the sum using Key-Value coding:
NSArray *profits = result of fetch request
NSNumber *totalProfit = [profits valueForKeyPath:@"@sum.profit"];
NSLog(@"%@", totalProfit);