考虑以下核心数据实体:
人员- personId:NSNumber,名称:NSString,位置:NSString
使用 Core Data,我正在尝试复制以下 SQL 查询:
SELECT `position`, COUNT(*) FROM `Person` GROUP BY `position`
以下是objective-c等价物:
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];
Person 实体肯定是填充的,但是,在执行上述代码时,results
数组是空的。想法?