ios - 核心数据: Do we need to re-fetch after every delete?

标签 ios core-data swift ios8 nsfetchedresultscontroller

嗨,请问有人可以帮助我吗?

我正在将核心数据tableview Controller 结合使用。我正在使用 NSFetchedResultsController (NSFRC)NSManagedObjectContext (NSMOC)

1)我正在 View 中执行 NSFRC.performFetch 已加载 2)当用户删除一行时,我正在执行 NSMOC.deleteObject

应用程序崩溃,提示删除后行数没有减少

在删除后执行 NSFRC.performFetch 即可解决问题。但我认为它应该可以工作,而无需我们强制获取?请有人向我解释一下吗?顺便说一句,我正在使用 IOS 8(beta 5)和 Swift

最佳答案

没有。您可以实现 NSFetchedResultsControllerDelegate 方法来捕获更改,以便在下划线数据更改(例如,删除和添加)时通知 NSFetchedResultsController。

- (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
{
    UITableView *tableView = self.tableView;

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

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

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

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


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

关于ios - 核心数据: Do we need to re-fetch after every delete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343626/

相关文章:

ios - swift:带按钮的动画

javascript - 从 iOS 浏览器中的后退缓存检索页面时持续触发的事件

ios - 如何检测哪个 segue 标识符激活了当前 View Controller

swift - 在另一个线程上保存 NSManagedContext

arrays - 使数组的所有值都为负数或改变符号

ios - 多行 UIAlertController 消息

ios - wifi Captive Portal下的iOS自动登录

objective-c - 使用来自 NSURL 的 UIImage 存储图像

iphone - core data中如何存储CGRect等东西

ios - 持久存储协调器核心数据错误:NSSQLiteErrorDomain = 522