本文介绍了带有谓词的 NSFetchedResultsController 忽略从不同 NSManagedObjectContext 合并的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有谓词的 NSFetchedResultsController 呈现表格视图内容:

I am presenting table view contents using NSFetchedResultsController which has a predicate:

[NSPredicate predicateWithFormat:@"visible == %@", [NSNumber numberWithBool:YES]]

在后台线程上使用单独的 NSManagedObjectContext 我更新了几个实体并将它们的 visible 值从 NO 更改为 YES.保存,合并主线程 NSManagedObjectContext 中的更改.但是 NSFetchedResultsControllerfetchedObjects 没有改变.此外,控制器不会在委托上调用 -controller:didChangeObject:....如果实体以相同的方式在主线程上更新(我的测试应用调用相同的方法),一切都会按预期进行.

On background thread using separate NSManagedObjectContext I update few of the entities and change theirs visible value from NO to YES. Save, merge changes in main thread's NSManagedObjectContext. But NSFetchedResultsController's fetchedObjects doesn't change. Also controller doesn't call -controller:didChangeObject:... on delegate. If entities are updated on main thread in identical manner (my test app calls the same method), everything works as expected.

Notification 的 NSUpdatedObjectsKey 也包含这些对象.

Also Notification's NSUpdatedObjectsKey contains those objects.

目前我找到的唯一解决方案是调用每个 NSUpdatedObjectsKey 实体:

Currently the only solutions I've found is to call for each of NSUpdatedObjectsKey entities:

NSManagedObjectContext *context = ... // main thread context
[context existingObjectWithID:[object objectID] error:nil]

此问题仅与之前与谓词不匹配的更新对象有关.

This issue is only with updated objects which previously didn't match the predicate.

我是否遗漏了一些明显的东西?

Am I missing something obvious?

推荐答案

原来 NSManagedObjectContext 没有为更新的对象触发 NSManagedObjectContextObjectsDidChangeNotification 事件,因为它没有为错误的对象.

Turns out main NSManagedObjectContext didn' t event fire NSManagedObjectContextObjectsDidChangeNotification for updated objects because it is not done for faulted objects.

通用修复(或跟踪需要这种处理的对象 ID):

Generic fix (or keep a track of object IDs that needs this treatment):

NSManagedObjectContext *context = [self managedObjectContext];
for(NSManagedObject *object in [[notification userInfo] objectForKey:NSUpdatedObjectsKey]) {
  [[context objectWithID:[object objectID]] willAccessValueForKey:nil];
}

[context mergeChangesFromContextDidSaveNotification:notification];

来自 NSManagedObject 类参考:

您可以使用nil 的键值以确保一个故障已触发,如图通过下面的例子.

这篇关于带有谓词的 NSFetchedResultsController 忽略从不同 NSManagedObjectContext 合并的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 13:36