核心数据:分组依据和计数结果返回空列表



请考虑以下核心数据实体:

人员 - personId: NSNumber, 姓名: NSString, 职位: NSString

使用核心数据,我正在尝试复制以下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数组为空。 思潮?

(来自我上面的评论:) 带有 NSDictionaryResultType 的获取请求仅返回存储文件中的对象,而不返回挂起的更改。因此,在执行该提取请求之前,您必须将上下文保存到持久存储中。

最新更新