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

后端 未结 1 1252
一生所求
一生所求 2021-02-05 14:10

I have a main NSManagedObjectContext that\'s created in the appDelegate.

Now, I\'m using another NSManagedObjectContext for editin

相关标签:
1条回答
  • 2021-02-05 14:54

    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];
    }
    
    0 讨论(0)
提交回复
热议问题