mon*_*eta 14 cocoa core-data objective-c nsmanagedobjectcontext
我有一个主要的NSManagedObjectContext,它是在appDelegate中创建的.
知道,我正在使用另一个NSManagedObjectContext来编辑/添加新对象而不影响主NSManagedObjectContext,直到我保存它们.
当我保存第二个NSManagedObjectContext时,更改不会反映在主NSManagedObjectContext中,但如果我从模拟器打开.sqlite数据库,则更改已正确保存到.sqlite数据库中.无论我是否再次获取数据,即使我创建了第三个NSManagedObjectContext,我也看不到第二个NSManagedObjectContext的更改,但此时这些更改都在磁盘上...
如果我退出并打开应用程序,则所有更改都在那里.
是什么导致主NSManagedObjectContext不能看到商店的新变化?
在此方法之前,我使用相同的NSManagedObjectContext和undoManager,但我想将其更改为使用两个不同的NSManagedObjectContext.
谢谢,
米
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
oct*_*cty 28
如果您尚未这样做,我建议您阅读有关Core Data:Change Management的Apple文档.
您需要通知第二个上下文中保存的更改的第一个上下文.保存上下文时,它会发布一个NSManagedObjectContextDidSaveNotification.注册该通知.在处理程序方法中,将通过第二个上下文保存的更改合并到第一个上下文中.例如:
// 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];
Run Code Online (Sandbox Code Playgroud)
通知处理程序:
- (void)handleDidSaveNotification:(NSNotification *)note {
[firstManagedObjectContext mergeChangesFromContextDidSaveNotification:note];
}
Run Code Online (Sandbox Code Playgroud)