gpt4 book ai didi

objective-c - 使用 Group By Count 获取核心数据属性

转载 作者:太空狗 更新时间:2023-10-30 03:29:04 25 4
gpt4 key购买 nike

这是我想为 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"];

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

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

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

关于objective-c - 使用 Group By Count 获取核心数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14145423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com