使用“to many”关系从NSFetchedResultsController派生UITableView节

我的核心数据模型如下所示:

article <--->> category 

是否可以使用NSFetchedResultsController来产生一个看起来像这样的UITableView?

 Category 1 - Article A - Article B - Article C Category 2 - Article A - Article D - Article E - Article F Category 3 - Article B - Article C 

具体而言,我对每个UITableView部分具有唯一标题(例如“类别1”,“类别2”)的(边缘?)情况感兴趣,但同一对象可以存在于多个部分中(例如,在类别1和类别2中)。

我search了苹果的Core Data文档,花了两天的时间仔细阅读这些问题,但是,唉,连这个也不知道是否可行,更别提怎么实现了。 感谢任何帮助或指向以前回答的问题。 我当然找不到它。

是的,这很容易,尽pipe有一百万种方法可以做到这一点。

您的视图控制器应该是UITableView的“数据源”,并返回有关行数的信息,然后返回每个单独行的内容。

在tableview中有一个“部分”的概念,你可以select每个类别都有一个。

例如,您可以创build一个NSFetchedResultsController来查找要显示的类别,然后使用它填充表视图部分,然后每个类别都将具有多对多的关系,以填充每个部分中的行。

像这样的东西应该让你开始(假设你的类别和物品实体都包含一个title属性):

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // return the number of categories [[self.categoryResultsController fetchedObjects] count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { // return the title of an individual category [[self.categoryResultsController.fetchedObjects objectAtIndex:section] valueForKey:@"title"]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // return the number of articles in a category MyCategory *category = [self.categoryResultsController.fetchedObjects objectAtIndex:section]; return category.articles.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // fetch a cached cell object (since every row is the same, we re-use the same object over and over) static NSString *identifier = @"ArticleCellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease]; } // find the category and article, and set the text of the cell MyCategory *category = [self.categoryResultsController.fetchedObjects objectAtIndex:indexPath.section]; cell.textLabel.text = [[category.articles objectAtIndex:indexPath.row] valueForKey:@"title"]; return cell; } 

您可以阅读关于这些方法的文档,以了解如何进一步定制它。

我会试图抛弃NSFetchResultsController因为我没有看到太多的好处,但是我没有太多的想法,所以我可能是错的。

你可以做的是:

  1. 执行所有category的提取请求并将其放置到NSArray 。 这些将是你的部分。
  2. 部分计数返回category的计数
  3. 对于行数返回self.category.articles的计数

以下是步骤2 + 3的一些示例代码

 // 2 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; { return [self.categories count]; } // 3 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; { return [[[self.categories objectAtIndex:section] articles] count]; }