使用Core Data使用SUM()进行GROUP BY

时间:2012-09-28 09:48:42

标签: objective-c ios core-data group-by

我遇到过类似的问题,但没有一个人有完整的例子说明如何实现它。

我试图翻译的SQL查询是:

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

我需要帮助调试以下的代码(目前fetchRequest返回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];

这是错误:

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'

1 个答案:

答案 0 :(得分:7)

上面的代码需要

[ex setName:@"somename"];

在执行fetchRequest之前。