我正在使用私有(private)托管对象上下文在持久存储中创建一些新对象,然后在保存私有(private) MOC 后,使用 mergeChangesFromContextDidSaveNotification
将它们合并到主 MOC 中。这工作正常,并根据需要更新 UI,NSManagedObjectContextWillSaveNotification
未在此处为 mainMOC
调用。
然后我使用 UI 对 mainMOC
进行一些更改,并监听 NSManagedObjectContextWillSaveNotification
。通知已发布,但它不仅包含我所做的编辑,还包含使用 mergeChangesFromContextDidSaveNotification
从 PrivateMOC
合并的对象。
有没有办法在后续的 contextDidChange
通知中忽略从另一个上下文合并到 mainContext
中的更改?
这是设置:
- (void) loadData {
privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSPrivateQueueConcurrencyType];
privateContext.persistentStoreCoordinator = self.mainContext.persistentStoreCoordinator;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextWillSave:)
name:NSManagedObjectContextWillSaveNotification
object: self.mainContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:record.recordType inManagedObjectContext: self.privateContext];
// fill in object
if ([self.privateContext hasChanges]) {
[self savePrivateContextAndMergeWithMainContext: self.privateContext];
}
}
- (void) savePrivateContextAndMergeWithMainContext: (NSManagedObjectContext *) privateContext {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(privateContextDidChange:) name:NSManagedObjectContextDidSaveNotification object:privateContext];
__block NSError *error = nil;
[privateContext performBlockAndWait:^{
NSLog(@"PrivateContext saved");
[privateContext save:&error];
}];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:privateContext];
if (error) {
NSLog(@"error = %@", error);
}
}
- (void) privateContextDidChange: (NSNotification *) notification{
[self.mainContext performBlockAndWait:^{
NSLog(@"merged into mainContext");
[self.mainContext mergeChangesFromContextDidSaveNotification:notification];
}];
}
这工作正常,保存私有(private)上下文并合并到 mainContext
不会触发 contextWillSave
通知。但是在从 UI(在主 MOC 上)编辑数据时会触发通知并包含之前使用私有(private) MOC 保存的数据。
希望这很清楚。让我知道我是否应该包括任何其他内容。
-- 更新--
似乎问题出在专门从私有(private)上下文中删除对象。从私有(private)上下文中删除并在主 MOC 上调用 mergeChangesFromContextDidSaveNotification
后,mainMoc 的 deletedObjects
集仍然显示已删除的对象。在私有(private)上下文中插入或更新不会发生这种情况。这在任何地方都有记录吗?解决方法是什么?
最佳答案
像这样修改 privateContextDidChange
...
- (void) privateContextDidChange: (NSNotification *) notification{
if (notification.object == PrivateMOC) {
[self.mainContext performBlockAndWait:^{
NSLog(@"merged into mainContext");
[self.mainContext mergeChangesFromContextDidSaveNotification:notification];
}];
}
}
...其中 PrivateMOC 是对私有(private)托管对象上下文的引用?
关于ios - 如何忽略 NSManagedObjectContextWillSaveNotification 中 mergeChangesFromContextDidSaveNotification 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733423/