这些是简单的提取。实际上,您可以使用 NSFetchedResultsController,并将“颜色”设置为部分名称,它会返回给您一个包含所有对象的数组,并且它们将按颜色分组。
就像是...
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Car"];
NSSortDescriptor *sectionSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sectionSortDescriptor, nameSortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"color" cacheName:@"CarCache"];
fetchedResultsController.delegate = self;
self.fetchedResultsController = fetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Handle error...
}
现在,您的数据将被分成多个部分,每种颜色一个部分,其中的值按名称排序。要获取数据,只需查看 FRC 的sections 属性。