(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.
Core Data: Group by and count results returns empty list
-
08-10-2022 - |
Frage
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?
Lösung
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow