如果您将获取请求设置为以字典形式返回结果,则您可以很好地控制分组。
http://mattconnolly.wordpress.com/2012/06/21/ios-core-data-group-by-and-count-results/ 和Core Data Fetching Properties with Group By Count 都包含很好的例子。第二个链接显示了如何通过关系的关键路径进行分组。
编辑:
在看到修改后的问题后,我稍微修改了一下。源码在Github上:https://github.com/halmueller/CoreDataGroupFetch
我找不到一个可以在单个查询中运行的解决方案。这是我能想到的最好的。它获取“键”字段的所有唯一值,然后遍历这些键并获取与该“键”匹配的所有对象。在第二次获取中,您可能想要获取 NSManagedObjects 而不是字典,具体取决于您要执行的操作。
NSFetchRequest* uniqueKeysFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KeyedName"];
uniqueKeysFetchRequest.propertiesToFetch = @[@"key"];
uniqueKeysFetchRequest.resultType = NSDictionaryResultType;
uniqueKeysFetchRequest.returnsDistinctResults = YES;
NSError* error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:uniqueKeysFetchRequest
error:&error];
NSLog(@"uniqueKeysFetchRequest: %@", results);
NSLog(@"distinct values for \"key\": %@", [results valueForKeyPath:@"@distinctUnionOfObjects.key"]);
for (NSString *thisKey in [results valueForKey:@"key"]) {
NSFetchRequest *oneKeyFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KeyedName"];
NSString *predicateString = [NSString stringWithFormat:@"key LIKE '%@'", thisKey];
oneKeyFetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString];
oneKeyFetchRequest.resultType = NSDictionaryResultType;
oneKeyFetchRequest.propertiesToFetch = @[@"name"];
NSLog(@"%@: %@", thisKey, [self.managedObjectContext executeFetchRequest:oneKeyFetchRequest error:&error]);
}
这会产生
results from uniqueKeysFetchRequest: (
{
key = K1;
},
{
key = K2;
}
)
distinct values for "key": (
K1,
K2
)
K1: (
{
name = N2;
},
{
name = N1;
},
{
name = N3;
}
)
K2: (
{
name = N2;
},
{
name = N1;
}
)
我也试过
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KeyedName"];
fetchRequest.propertiesToFetch = @[@"key", @"name"];
fetchRequest.propertiesToGroupBy = @[@"key", @"name"];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.returnsDistinctResults = YES;
NSError* error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&error];
NSLog(@"withKeypathStrings: %@", results);
NSLog(@"distinct values for \"key\": %@", [results valueForKeyPath:@"@distinctUnionOfObjects.key"]);
这可能更接近你想要的:
withKeypathStrings: (
{
key = K1;
name = N1;
},
{
key = K1;
name = N2;
},
{
key = K1;
name = N3;
},
{
key = K2;
name = N1;
},
{
key = K2;
name = N2;
}
)
distinct values for "key": (
K2,
K1
)