Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY with SUM() using Core Data

I came across similar questions but none of them had a complete example of how to accomplish it.

The SQL query I am trying to translate is this:

SELECT date, SUM(amount) FROM Table GROUP BY date;

I need help debugging the following piece code (currently the fetchRequest returns nil):

entity = [NSEntityDescription entityForName:@"Table" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSExpressionDescription* ex = [[NSExpressionDescription alloc] init];
[ex setExpression:[NSExpression expressionWithFormat:@"@sum.amount"]];
[ex setExpressionResultType:NSDecimalAttributeType];

[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"date", ex, nil]];
[fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObject:@"date"]];
[fetchRequest setResultType:NSDictionaryResultType ];

[self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

This is the error:

2012-09-28 13:58:46.319 App[12205:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
like image 465
Nikolay Spassov Avatar asked Sep 28 '12 09:09

Nikolay Spassov


1 Answers

The code above needs

[ex setName:@"somename"];

before executing the fetchRequest.

like image 141
Nikolay Spassov Avatar answered Oct 28 '22 02:10

Nikolay Spassov