Changes saved from one NSManagedObjectContext doesn't reflect on main NSManagedObjectContext

杀马特。学长 韩版系。学妹 提交于 2019-12-03 03:10:30
octy

If you haven't already done so, I suggest reading the Apple documentation on Core Data : Change Management.

You need to notify the first context of the changes that were saved through the second context. When saving a context, it posts a NSManagedObjectContextDidSaveNotification. Register for that notification. In the handler method, merge into the first context the changes saved through the second context. For example:

// 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];

Notification handler:

- (void)handleDidSaveNotification:(NSNotification *)note {
    [firstManagedObjectContext mergeChangesFromContextDidSaveNotification:note];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!