具有自定义单元格的NSFetchedResultsController

时间:2013-04-08 21:09:31

标签: uitableview core-data nsfetchedresultscontroller

我正在使用NSFetchedResultsController,我不知道如何解决当前的问题。 我的表视图中的标题是单元格而不是真正的标题,因为我不希望标题在滚动时粘在顶部。

信息非常明确:

CoreData: error: Serious application error.  An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:.  Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). with userInfo (null)

但插入1行后的部分中的行数需要为2!我怎样才能让表格视图知道这个?我已经在做这样的事了:

indexPath = [NSIndexPath indexPathForRow:indexPath.row + 1
                               inSection:section];

newIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row + 1
                                  inSection:section];

但是在这种特殊情况下它不起作用,在第一次崩溃之后一切都按照它应该的方式工作,因为这是唯一一次插入两个单元格而只有一个来自核心数据本身。

1 个答案:

答案 0 :(得分:1)

我终于找到了解决问题的方法!

我只是检查是否是第一次通过NSFetchedResultsController委托(didChangeObject :)添加来自NSFetchedResultsController的单元格,如果是,我手动添加另一行。

段:

- (void)controller:(NSFetchedResultsController *)controller
   didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath
{
    NSInteger section = 1;
    indexPath = [NSIndexPath indexPathForRow:indexPath.row + 1
                                   inSection:section];

    NSMutableArray *newIndexPaths = [NSMutableArray array];
    id <NSFetchedResultsSectionInfo> sectionInfo = [controller.sections objectAtIndex:0];
    if ([sectionInfo numberOfObjects] == 1) {
        newIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row
                                          inSection:section];
        [newIndexPaths addObject:newIndexPath];
    }

    newIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row + 1
                                      inSection:section];
    [newIndexPaths addObject:newIndexPath];

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:newIndexPaths
                                  withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                                  withRowAnimation:UITableViewRowAnimationFade];
            break;
        default:
            break;
    }
}