2011-05-27 24 views
13

我有一个主要的NSManagedObjectContext,它是在appDelegate中创建的。从一个NSManagedObjectContext保存的更改不反映在主NSManagedObjectContext

知道,我正在使用另一个NSManagedObjectContext编辑/添加新的对象,而不影响主NSManagedObjectContext,直到我保存它们。

当我保存第二个NSManagedObjectContext时,更改不会反映在主NSManagedObjectContext中,但是如果从模拟器打开.sqlite数据库,则更改已正确保存到.sqlite数据库中。无论我是否再次获取数据,即使创建了第三个NSManagedObjectContext,我也无法看到第二个NSManagedObjectContext发生的更改,但这些更改现在都在磁盘上...

如果我退出并打开应用程序,所有的变化都在那里。

什么会导致主NSManagedObjectContext不能看到商店的新变化?

在这种方法之前,我使用了相同的NSManagedObjectContext和undoManager,但我想将它改为使用两个不同的NSManagedObjectContext。

谢谢,

m。

second NSManagedObjectContext save: 
----------------------------------------- 

    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]); 
     } 
    } 

回答

26

如果您还没有这样做的话,我建议您阅读苹果文档上Core Data : Change Management.

您需要通知的,将其通过第二上下文保存下来的修改第一上下文。保存上下文时,会发布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]; 

通知处理程序:

- (void)handleDidSaveNotification:(NSNotification *)note { 
    [firstManagedObjectContext mergeChangesFromContextDidSaveNotification:note]; 
} 
+0

我认为NSManagedObjectContextDidSaveNotification没有必要/强制性的,我读过其他职位,那就是我不明白。我会尝试你的建议,并在这里再次发布。谢谢! – mongeta 2011-05-27 18:45:47

+1

谢谢,完美无缺! – mongeta 2011-05-28 16:29:10

+0

不客气! – octy 2011-05-29 02:10:23

相关问题