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

时间:2014-02-08 20:04:33

标签: core-data ios7 nspredicate nsexpression nsattributedescription

考虑以下核心数据实体:

- 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数组为空。想法?

1 个答案:

答案 0 :(得分:1)

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