0

考虑以下核心数据实体:

人员- 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数组是空的。想法?

4

1 回答 1

1

(根据我上面的评论:)一个 fetch 请求NSDictionaryResultType只返回存储文件中的对象,而不是挂起的更改。因此,您必须在执行该获取请求之前将上下文保存到持久存储中。

于 2014-02-08T23:31:03.787 回答