0

我有一个使用NSFetchedResultsController附加到UITableView.

我遇到了一个非常奇怪的问题,当在数据库中插入一个应该出现在表格底部的新项目时,最后一个项目的单元格被新插入的项目替换 - 所以屏幕现在显示我刚刚插入的项目,但之前的项目丢失了。进一步的插入表现出相同的行为,表不会增长,并且最后一项被任何新项替换。

当应用程序重新启动时,完整的数据表会按原样显示(换句话说,被覆盖的单元格在数据库中仍然有数据)。获取结果控制器似乎忘记了新项目应该去哪里。

之前和之后的示例:

前

后

添加:

现有的代码controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    UITableView *fetchTableView = [self tableViewForFetchedResultsController:controller];
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [fetchTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
               break;
///....
    }
4

2 回答 2

0

这种现象似乎表明在有问题的更新代码中,您正在更新最后一个单元格,而不是插入一个单元格。

使用
insertRowsAtIndexPaths:withRowAnimation:而不是
reloadRowsAtIndexPaths:withRowAnimation:

于 2013-02-09T11:09:39.277 回答
0

我猜您在方法中使用了错误的参数:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath 

插入行时要小心使用newIndexPath参数,而不是:indexPath

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        default:
            break;
    }
}
于 2013-02-09T11:12:36.063 回答