从一个NSManagedObjectContext保存的更改不会反映在主NSManagedObjectContext上

问题描述 投票:14回答:1

我有一个在NSManagedObjectContext创建的主要appDelegate

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

当我保存第二个NSManagedObjectContext时,更改不会反映在主NSManagedObjectContext中,但如果我从模拟器打开.sqlite数据库,则更改已正确保存到.sqlite数据库中。如果我再次获取数据无关紧要,或者即使我创建了第三个NSManagedObjectContext,我也无法从第二个NSManagedObjectContext看到这些更改,尽管这些更改确实存在于磁盘上。

如果我退出并重新打开应用程序,则会有所有更改。

是什么导致主要的NSManagedObjectContext看不到持久存储中出现的新变化?

在这种方法之前,我使用单个NSManagedObjectContextundoManager,但我想改变它使用两个不同的NSManagedObjectContexts。

第二个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]);
        }
    }
objective-c cocoa core-data nsmanagedobjectcontext
1个回答
27
投票

如果你还没有这样做,我建议你阅读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];

通知交易:

- (void)handleDidSaveNotification:(NSNotification *)note {
    [firstManagedObjectContext mergeChangesFromContextDidSaveNotification:note];
}
© www.soinside.com 2019 - 2024. All rights reserved.