在NSFetchedResultsController的两个部分中显示托管对象

时间:2012-05-20 12:42:41

标签: core-data nsfetchedresultscontroller

我有一个NSManagedObject,它有三个属性:

  1. 标题(NSString *
  2. 标题(NSString *
  3. 收藏(BOOL
  4. 我想使用以下方案显示这些对象的列表:

    • 收藏夹
      • 对象1
      • 对象3
    • 一个标题
      • 对象2
      • 对象3
    • B标题
      • 对象1
      • 对象4

    使用NSFetchedResultsController有没有办法做到这一点?我尝试按favoriteheader对其进行排序无效,因为一旦将对象分配到收藏夹部分 - 它将不会显示在其标题的部分中。有什么技巧可以用吗?我应该执行两次抓取并将结果重新格式化为一个嵌套数组吗?

1 个答案:

答案 0 :(得分:1)

使用两个单独的NSFetchedResultsController's

然后,您需要在各种委托方法中考虑到这一点。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.mainFetchedResultsController sections] count] + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return [[[self.favFetchedResultsController sections] objectAtIndex:section] numberOfObjects];
    } else {
        return [[[self.mainFetchedResultsController sections] objectAtIndex:section - 1] numberOfObjects];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    
    if (section == 0) {
        return @"Favourites";
    } else {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[self.mainFetchedResultsController sections] objectAtIndex:section - 1];
        return [sectionInfo name];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Object *object = nil;

    if (indexPath.section == 0) {
        object = [self.favFetchedResultsController objectAtIndexPath:indexPath];
    } else {
        NSIndexPath *mainIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section -1];
        object = [self.mainFetchedResultsController objectAtIndexPath:mainIndexPath];
    }

    UITableViewCell *cell = ...

    ...

    return cell;
}