当didChangeObject被称为NSFetchedResultsController时,UITableView不会更新

时间:2013-10-10 21:31:02

标签: ios uitableview ios7 nsfetchedresultscontroller

我正在使用带有UITableView的NSFetchedResultsController。我成功接收到- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath的委托调用,但我在UITableView中插入/更新/删除行所做的任何更改都没有显示出来。我甚至只是尝试在UITableView上设置背景颜色以查看是否会显示任何更改,但除非我按下新的视图控制器然后弹回,否则它们不会显示。然后我会看到背景颜色和表格更新。

我对didChangeObject:方法的实现实际上只是样板模板:

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

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

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath
{
    UITableView *tableView = self.tableView;

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            tableView.backgroundColor = [UIColor redColor];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            tableView.backgroundColor = [UIColor blueColor];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

我在导航栏中添加了一个带有IBAction的按钮,只需调用[self.tableView reloadData];,每当我点击它时,所有插入和更新都会显示在表格中。但是,随着变化的发生,它们不会出现。

有什么问题?

1 个答案:

答案 0 :(得分:3)

看起来委托调用didChangeObject(以及其他方法)没有发生在主线程上,这意味着他们无法更新UI,但这些更改只是默默地被删除。

我更新了上面包含的三个方法,以便在主线程上调度这些方法的主体,一切都按预期工作。以下是一个例子:

dispatch_sync(dispatch_get_main_queue(), ^{
        [self.tableView beginUpdates];
});
相关问题