这是我想为 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 作为组关系 - 这可能吗?
Mark
setPropertiesToGroupBy
of NSFetchRequest
接受一个数组NSPropertyDescription
or NSExpressionDescription
物体,或键路径字符串。在您的情况下,您可以使用键路径字符串:
[fetchGroupSummary setPropertiesToGroupBy:[NSArray arrayWithObject:@"group.name"]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)