iphone - NSFetchedResultsController 的 didChangeObject 未调用

标签 iphone objective-c ios nsfetchedresultscontroller

我已指定 NSFetchtedResultsController 作为属性...

@property (nonatomic, strong) NSFetchedResultsController *controller;

...并将委托(delegate)设置为我的类(class)。

self.controller.delegate = self;

然后我实现了标题中提到的方法并在其中放置了一个断点。

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

    => BREAKPOINT <=

    }

我已经为 Controller 创建了获取请求,如下所示:

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Post"]; 
   // ... some sort ...
    self.controller = [[NSFetchedResultsController alloc]
                       initWithFetchRequest:fetchRequest
                       managedObjectContext:self.context
                       sectionNameKeyPath:nil
                       cacheName:@"cache"];

现在,我在同一上下文中的另一个类中存储了一些“Post”类型的 NSManagedObject,但是 didChangeObject 方法从未被调用(我的断点就在其中) )。

有人知道出了什么问题吗?

更新#1:从服务器获取一些帖子并将其存储到上下文中的类是使用 GCD 异步执行的。

更新#2:我以另一种方式尝试过,因为它无法在多线程环境中使用上下文。 (感谢斯文娜) 现在,ServerConnection 在异步 block 中运行(使用 GCD)并在主线程上执行选择器。此选择器方法将帖子存储在数据库中,并且应该更新 TableView 。基本上,我认为当我在此上下文中存储某些内容时,应该自动调用 didChangeObject 方法吗?但事实并非如此。 :-/

我添加了一个简短的序列图来说明我当前的状态。 sample sequence diagram 有谁知道为什么这不起作用?请耐心等待。我是 CoreData 和 Objective-C 的新手。 :)

最佳答案

Update #1: The class which fetches some posts from a server and stores it into the context is executed asynchronously using GCD.

如果是这种情况,您如何为 GCD block 创建托管对象上下文? 上下文或托管对象都不是线程安全的,并且不能在线程之间传递。此外,对一个线程上的上下文所做的更改不会自动传播到其他线程上的上下文。在 iOS5 之前,这意味着监听 NSManagedObjectContextDidSaveNotification 并使用 mergeChangesFromContextDidSaveNotification: 方法将其合并到 NSFetchedResultsController 实例中以查看它。

顺便说一句,图表很棒:)

能否请您在以下位置显示代码:

  1. 创建您的上下文
  2. 在主线程上执行您的 block 以插入 数据

关于iphone - NSFetchedResultsController 的 didChangeObject 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769305/

相关文章:

iphone - iOS - 如何在 UITabBar 中重新加载不同的 ViewController

iphone - 在 iOS 中使用 AVCaptureMovieFileOutput 和 AVCaptureVideoDataOutput 暂停和恢复视频捕获

iphone - 为什么从导航堆栈中弹出 View 时键盘不显示?

ios - Xcode 11.1 在iOS 13.1.2设备上运行测试,设置断点

ios - iOS 7 中 appStoreReceiptURL (NSData) 返回的无效交易收据

ios - 将来自 VTCompressionSession 的压缩帧与音频数据混合到 MPEG2-TS 容器中以进行网络流式传输

iphone - 我可以垂直显示 UISegmentedControl 对象吗?

objective-c - 如何在 Objective-C 中创建文件范围类?

iphone - 如何在应用更新下载后再次调用 didFinishLaunchingWithOptions

iphone - 将 UIView 转换为 UITableView