in my app, I use a background contexts to synchronize data. Basically, all user data is in Core Data and when something changes, the background context will upload the changes to the server. Also, there is another context which polls the server every few minutes to see if there are any changes there. If so, it saves the changes to the local database.
My current approach is, that when the application starts, I create a new background context (persistentContainer.newBackgroundContext()) and use it indefinetly.
Obviously, the other approach would be to create a new background context everytime I need to run the synchronization and then throw it away when the synchronization finishes.
I wonder which approach is better.
For example, one issue I ran into is that the "long lived" backround context doesn't always see the changes made by other contexts. I use "automaticallyMergesChangesFromParent = true" but that doesn't seem to work in all cases. So, I ended up doing things like:
self.backgroundContext.refresh(dbEntity, mergeChanges: true). My understanding is that the "parent" for backgroundContext is the actual SQLite database when the context is created using persistentContainer.newBackgroundContext()
If someone has a link to an article which would clearly explain everything around ManagedObjectContexts and merging objects between them, I'd love to see it. I read a few articles but I still must be missing something.
Thanks a lot