Strange behavior when using child/parent NSManagedObjectContext

后端 未结 2 924
萌比男神i
萌比男神i 2021-02-10 15:54

I\'m developing an application where I need to both calculate things (multiple seconds operations) and write things (sync data with a server) on a background thread.

Bec

相关标签:
2条回答
  • 2021-02-10 16:01

    I had this problem and the solution was making sure all operations on the parent MOC are done with performBlock:, even the initial setup:

        parentManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [parentManagedObjectContext performBlock:^{
            [parentManagedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
            [parentManagedObjectContext setPersistentStoreCoordinator:coordinator];
        }];
    

    Once I did this, my child MOCs started picking up changes.

    0 讨论(0)
  • 2021-02-10 16:04

    My solution was to:

    1) Use the background MOC as the parent MOC and the main MOC as a child. As a bonus I don't need to save the main MOC to get the permanent IDs.

    [DC.backgroundMOC performBlock:^{
        // Add, save and update managed objects
        [DC saveContext]; // The changes is being pushed to the main context
    }];
    

    2) Use NSManagedObjectContextDidSaveNotification to keep the main MOC up to date (the main MOC is updating the UI)

    - (void) backgroundMOCSaved:(NSNotification*)notification {
        [mainMOC performBlock:^{
            [mainMOC mergeChangesFromContextDidSaveNotification:notification];
        }];
    }
    
    0 讨论(0)
提交回复
热议问题