核心数据导致endUpdates中的异常

时间:2013-09-30 20:58:37

标签: ios objective-c core-data

我有一个使用核心数据来驱动UITableView部分的应用。它使用所有示例项目使用的标准NSFetchedResultsControllerDelegate实现。但是,偶尔但不可靠,调用[self.tableView endUpdates]会引发以下异常:

CoreData: error: Serious application error.  An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:.  attempt to insert row 3 into section 1, but there are only 3 rows in section 1 after the update with userInfo (null)

之后,表视图只包含当时可见的单元格和空白区域(但仍可滚动)。什么都没有修复它,但重新启动应用程序。我确定应用程序会崩溃,除了NSFetchedResultsController正在捕获异常。

应用重新启动后,导致回调的数据就会出现。当然,第1部分只有3行(或者说例外)。 那么为什么Core Data会告诉我插入一个不存在的行呢?

- (void)reloadFetch
{
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        TULogError(@"Unresolved error %@, %@", error, [error userInfo]);
        [[TCCacheController sharedController] clearData];
    }

    [self.tableView reloadData];
}

- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController == nil) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"FeedItem"];
        fetchRequest.fetchBatchSize = 20;
        fetchRequest.predicate = [NSPredicate predicateWithFormat:@"city = %@", [TCCity currentCity]];
        fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"updatedAt" ascending:NO] ];
        fetchRequest.relationshipKeyPathsForPrefetching = @[
                                                            @"user",
                                                            @"responses",
                                                            ];

        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                        managedObjectContext:[TCCacheController sharedController].mainContext
                                                                          sectionNameKeyPath:@"day"
                                                                                   cacheName:nil];
        _fetchedResultsController.delegate = self;

        [self reloadFetch];
    }

    return _fetchedResultsController;
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller
  didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex
     forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (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;
        } case NSFetchedResultsChangeDelete: {
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        } case NSFetchedResultsChangeUpdate: {
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        } case NSFetchedResultsChangeMove: {
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        }
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}

2 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,但是我将自己的自定义部分添加到NSFetchedResultsController返回的结果中。这样做时,我必须确保在管理返回的结果时调整索引路径。我错过了在didChangeObject方法中处理索引路径。

我实现了以非常强力的方式更改索引路径,但在寻找这个问题时,我在这篇SO帖子中找到了一个非常有用且更优雅的解决方案:NSFetchedResultsController prepend a row or section(参见JosehpH的回答)。

答案 1 :(得分:1)

尝试将tableViewSection设置为硬编码,如下所示:

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

为我修好了。