I find this method (roughly similar to the accepted answer) a little cleaner and clearer. This is the equivalent of SQL:
SELECT COUNT(*), a_value FROM my_table GROUP BY a_value;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[MyTable className]]; // create expression for grouped column NSExpressionDescription *aValueDescription = [[NSExpressionDescription alloc] init]; aValueDescription.name = @"aValue"; // name of key in result dictionary aValueDescription.expression = [NSExpression expressionWithFormat:@"aValue"]; aValueDescription.expressionResultType = NSObjectIDAttributeType; // create expression for count NSExpressionDescription *countDescription = [[NSExpressionDescription alloc] init]; countDescription.name = @"count"; // name of dictionary key in result dictionary countDescription.expression = [NSExpression expressionWithFormat:@" aValue.@count "]; countDescription.expressionResultType = NSInteger32AttributeType; // fill out fetch request fetchRequest.propertiesToGroupBy = @[@"aValue"]; fetchRequest.propertiesToFetch = @[aValueDescription, countDescription]; //fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"count" ascending:NO]]; // not sure why this crashes fetchRequest.resultType = NSDictionaryResultType; // required for "group by" requests NSError *error = nil; NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
The returned results is an array of NSDictionary. Please note: the name description properties can be whatever you want - these are just the key names in the returned dictionaries. You can add a predicate to a query to filter rows from a table; this code returns all rows.
The bonus points to everyone who can tell me how to get the sort descriptor to work ...
Demitri
source share