我正在尝试获取所有类别及其子类别,并将它们全部显示在表格中。我知道如何获取所有类别,但我需要获取所有子类别,并使用获取结果 Controller 按类别对它们进行排序。有什么建议吗?
最佳答案
您可以创建一个获取的结果 Controller 来获取 SubCategory 实体并根据 Category 将它们分组为部分:
// Fetch "SubCategory" entities:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"];
// First sort descriptor for grouping the cells into sections, sorted by category name:
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"category.name" ascending:YES];
// Second sort descriptor for sorting the cells within each section:
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:@"category.name"
cacheName:nil];
[self.fetchedResultsController setDelegate:self];
NSError *error;
BOOL success = [self.fetchedResultsController performFetch:&error];
然后您可以使用 NSFetchedResultsController Class Reference 中描述的常用 TableView 数据源方法。 .
这为您提供了一个表格 View ,其中每个类别都有一个表格 View 部分。
关于iphone - 核心数据获取到许多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993280/