考虑以下核心数据实体:
人 - 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
数组为空。想法?
答案 0 :(得分:1)
(来自我的上述评论:)带有NSDictionaryResultType
的获取请求仅返回商店文件中的对象,而不是待处理的更改。因此,您必须在执行该获取请求之前将上下文保存到持久性存储。