iphone - 核心数据获取到许多

标签 iphone objective-c ios core-data

我正在尝试获取所有类别及其子类别,并将它们全部显示在表格中。我知道如何获取所有类别,但我需要获取所有子类别,并使用获取结果 Controller 按类别对它们进行排序。有什么建议吗?

enter image description here

最佳答案

您可以创建一个获取的结果 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/

相关文章:

objective-c - 理解 iOS 泄漏调用堆栈跟踪

ios - 为什么 Xcode 会创建无效代码?

ios - 正确设置 numberOfRowsInSection

iphone - 如何让 super View 拦截按钮触摸事件?

ios - 大多数时候 HTML 不会第一次加载

iPhone - 如何测量 PCM 编码信号的幅度

ios - ios7 sdk 中的 MKMapView 内存问题

ios - AB地址簿崩溃 CFStringRef

ios - Swift 取消 ActivityViewController 导致 fatal error

iphone - 表格包含这么多Sections,如何单独增加每一行的Label值