1

我正在使用 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行后section的行数需要为2!我怎样才能让表格视图知道这一点?我已经在做这样的事情了:

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

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

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

4

1 回答 1

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;
    }
}
于 2013-04-09T09:35:56.307 回答