我正在使用私有托管对象上下文在持久性存储中创建一些新对象,然后在保存私有MOC之后,使用mergeChangesFromContextDidSaveNotification将它们合并到主MOC中.这工作正常,并根据需要更新UI,并且此处不为mainMOC调用NSManagedObjectContextWillSaveNotification.
@H_404_19@解决方法@H_502_20@
然后我使用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]; }]; }
这样可以正常工作并保存私有上下文并且合并到mainContext中不会触发contextWillSave通知.但是,在从UI(在主MOC上)编辑数据时,会触发通知并包含先前使用私有MOC保存的数据.
希望很清楚.如果我应该包含其他任何内容,请告诉我.
– 更新 –
似乎问题是专门从私有上下文中删除对象.从私有上下文中删除,并在主MOC上调用mergeChangesFromContextDidSaveNotification后,mainMoc的deletedObjects集仍然显示已删除的对象.私有上下文中的插入或更新不会发生这种情况.这在任何地方记录?可能的解决方法是什么?
像这样修改privateContextDidChange ……
- (void) privateContextDidChange: (NSNotification *) notification{ if (notification.object == PrivateMOC) { [self.mainContext performBlockAndWait:^{ NSLog(@"merged into mainContext"); [self.mainContext mergeChangesFromContextDidSaveNotification:notification]; }]; } }
…其中PrivateMOC是对私有托管对象上下文的引用?