如果您將提取請求設置爲以字典形式返回結果,那麼對分組有很多控制權。
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
我無法獲得可以在單個查詢中工作的解決方案。這是我能想到的最好的。它獲取「key」字段的所有唯一值,然後迭代這些鍵並獲取與該「key」匹配的所有對象。在第二次讀取中,您可能需要獲取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
)
尼斯,對於計數工作。即「鍵」,「3」,但不是我想要的... group_concat給我的結果像「密鑰」,「data1,data2,data3」 – Noah