I have a Core Data database with an entity "Event" and an attribute "eventDate" with "Date" type. The task is showing events grouping by date and showing the number (@"count") of events date by date. For example eventDate (mm-dd-yyyy) data:
events eventDate
event 1 01-01-2013
event 2 01-01-2013
event 3 01-02-2013
event 4 01-03-2013
...
Result in table view:
date count
01-01-2013 2
01-02-2013 1
01-03-2013 1
...
Don't like to fetch all database as it could be big so I use aggregate operation not to fetch every object. The code is working without error but the resulting array is empty. My guess the problem is the grouping with date type attribute and the NSAttribute/attributeType but couldn't make it work. The code in the Event's category file is:
+ (NSArray *)aggregateOperationOnEvent:(NSString *)attributeName withFunction:(NSString *)function withPredicate:(NSPredicate *)predicate inManagedObjectContext: (NSManagedObjectContext*)context {
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
NSAttributeDescription* attributeDesc = [entity.attributesByName objectForKey:attributeName];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: attributeName];
NSExpression *functionExpression = [NSExpression expressionForFunction: [NSString stringWithFormat:@"%@:", function] arguments: [NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: function];
[expressionDescription setExpression: functionExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
[request setPropertiesToFetch:[NSArray arrayWithObjects:attributeDesc, expressionDescription, nil]];
[request setPropertiesToGroupBy:[NSArray arrayWithObject:attributeDesc]];
[request setResultType:NSDictionaryResultType];
if (predicate != nil)
[request setPredicate:predicate];
NSError* error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
return results;
}