core-dataios7nspredicatensexpressionnsattributedescription

Core Data: Group by and count results returns empty list


Consider the following Core Data entity:

Person - personId: NSNumber, name: NSString, position: NSString

Using Core Data, I'm trying to replicate the following SQL query:

SELECT `position`, COUNT(*) FROM `Person` GROUP BY `position`

Below is the objective-c equivalent:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person"]

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"position"];
NSExpression *countExpression = [NSExpression expressionForFunction:@"count:" arguments:@[keyPathExpression]];

NSAttributeDescription *positionDescription = [entity.attributesByName objectForKey:@"position"];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];

[expressionDescription setName:@"count"];
[expressionDescription setExpression:countExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];

[request setPropertiesToFetch:@[positionDescription, expressionDescription]];
[request setPropertiesToGroupBy:@[positionDescription]];
[request setResultType: NSDictionaryResultType];

NSError *error = nil;
NSArray *results = [context executeFetchRequest: request error: &error];

The Person entity is definitely populated, however, when executing the above code, the results array is empty. Thoughts?


Solution

  • (From my above comments:) A fetch request with NSDictionaryResultType returns only the objects from the store file, not the pending changes. Therefore you have to save the context to the persistent store before executing that fetch request.