Objective c 按计数分组的核心数据获取属性

Objective c 按计数分组的核心数据获取属性,objective-c,core-data,Objective C,Core Data,这是我要为核心数据编写的查询的SQL版本: SELECT Group.Name, COUNT(Item.Name) FROM Item INNER JOIN Group ON Item.GroupID = Group.ID GROUP BY Group.Name 到目前为止,我得到的是: NSFetchRequest* fetchGroupSummary = [NSFetchRequest fetchRequestWithEntityName:@"Item"]; NSEntityDescri

这是我要为核心数据编写的查询的SQL版本:

SELECT Group.Name, COUNT(Item.Name)
FROM Item INNER JOIN Group ON Item.GroupID = Group.ID
GROUP BY Group.Name
到目前为止,我得到的是:

NSFetchRequest* fetchGroupSummary = [NSFetchRequest fetchRequestWithEntityName:@"Item"];

NSEntityDescription* entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:[[CoreDataManager sharedInstance] managedObjectContext]];

NSAttributeDescription* groupName = [entity.relationshipsByName objectForKey:@"group"];
NSExpression *countExpression = [NSExpression expressionForFunction: @"count:" arguments: [NSArray arrayWithObject:[NSExpression expressionForKeyPath: @"name"]]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];

[expressionDescription setName: @"count"];
[expressionDescription setExpression: countExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"group.sort" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"group.stage == %@", stage];

[fetchGroupSummary setEntity:entity];
[fetchGroupSummary setSortDescriptors:@[sortDescriptor]];
[fetchGroupSummary setPropertiesToFetch:[NSArray arrayWithObjects:groupName, expressionDescription, nil]];
[fetchGroupSummary setPropertiesToGroupBy:[NSArray arrayWithObject:groupName]];
[fetchGroupSummary setResultType:NSDictionaryResultType];
[fetchGroupSummary setPredicate:predicate];

NSError* error = nil;
groups = [[[CoreDataManager sharedInstance] managedObjectContext] executeFetchRequest:fetchGroupSummary error:&error];

expressionDescription = nil;
这几乎为我提供了一切,但是我想指定group.name,而不是groupName作为组关系-这可能吗


NSFetchRequest
的Mark

setPropertiesToGroupBy
接受
NSPropertyDescription
NSExpressionDescription
对象或键路径字符串的数组。在您的情况下,可以使用keypath字符串:

[fetchGroupSummary setPropertiesToGroupBy:[NSArray arrayWithObject:@"group.name"]];

您是否尝试过
[fetchGroupSummary setPropertiesToGroupBy:[NSArray arrayWithObject:@“group.name”]
?Martin,这非常有效!如果您将其添加为答案,我将接受。我正在尝试按其中的属性对结果集进行分组。但它会崩溃,错误为无效的获取请求:GROUP BY需要NSDictionaryResultType。这是我的密码。你能告诉我我做错了什么吗?@Isuru:
fetchRequest.resultType=.DictionaryResultType
。此处描述了(目标-)C枚举和Swift枚举之间的映射:。我刚才这样做了,但我现在遇到了一个新错误。查询中,GROUP BY组件中的SELECT子句只能包含GROUP BY或AGGRATE中命名的属性functions@Isuru:您可能还必须设置
属性estofetch
。似乎不起作用。我指定了每个属性名称,但仍然存在相同的错误。:/我是否可以单独提出一个问题,提供更多细节?