问题描述
||
我在main1ѭ中创建了一个主
NSManagedobjectContext
。
现在,我将使用另一个“ 0”来编辑/添加新对象,而不影响主“ 0”,直到保存它们。
当我保存第二个“ 0”时,所做的更改未反映在主“ 0”中,但是,如果我从模拟器中打开.sqlite数据库,则更改已正确保存到.sqlite数据库中。再次获取数据还是创建第三个ѭ0doesn无关紧要,尽管此时这些更改确实已存在于磁盘上,但我看不到第二个NSManagedobjectContext
的更改。
如果我退出并重新打开该应用程序,则所有更改都在那里。
是什么导致主“ 0”看不到持久性存储中存在的新更改?
在使用这种方法之前,我只使用了一个“ 0”和“ 10”,但是我想将其更改为使用两个不同的“ 0”。
第二个“ 0”保存:
NSError* error = nil;
if ([managedobjectContext hasChanges]) {
NSLog(@\"This new object has changes\");
}
if (![managedobjectContext save:&error]) {
NSLog(@\"Failed to save to data store: %@\",[error localizedDescription]);
NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if(detailedErrors != nil && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors) {
NSLog(@\" DetailedError: %@\",[detailedError userInfo]);
}
}
else {
NSLog(@\" %@\",[error userInfo]);
}
}
解决方法
如果您尚未这样做,建议您阅读Apple文档“核心数据:变更管理”。
您需要将通过第二个上下文保存的更改通知第一个上下文。保存上下文时,它会贴上“ 14”字样。注册该通知。在处理程序方法中,将通过第二个上下文保存的更改合并到第一个上下文中。例如:
// second managed object context save
// register for the notification
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(handleDidSaveNotification:)
name:NSManagedObjectContextDidSaveNotification
object:secondManagedObjectContext];
// rest of the code ommitted for clarity
if (![secondManagedObjectContext save:&error]) {
// ...
}
// unregister from notification
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:secondManagedObjectContext];
通知处理程序:
- (void)handleDidSaveNotification:(NSNotification *)note {
[firstManagedObjectContext mergeChangesFromContextDidSaveNotification:note];
}