1 year ago

#279710

test-img

iDev

How to synchronise viewContext and backgroundContext in iOS CoreData?

Anyone can guide me on how can I synchronize mainContext and backgroundContext updates?

Here is a brief idea of what we have done and what issue we are facing right now.

We have created two context objects from the below code.

  1. mainContext
lazy var mainContext = NSManagedObjectContext = { let context =
self.persistantContainer.viewContext
    context.mergePolicy = NSMergePolicy( merge: . mergeByPropertyObjectTrumpMergePolicyType)
    return context
 }()
  1. backgroundContext
    lazy var backgroundContext = NSManagedObjectContext = {       
     let context = self.persistantContainer.newBackgroundContext()         
         context.mergePolicy = NSMergePolicy( merge: .mergeByPropertyObjectTrumpMergePolicyType)
     return context
     }()

Now when I have inserted anything with the help of mainContext, and trying to retrieve it with backgroundContext, I am not able to get the data. It's working fine if the context is the same.

Also if I try to insert via backgroundContext and retrieve via main context, it's giving me no result.

The method I used to save data in the main context. A similar method I have also created for background context.

if mainContext.hasChanges{
    do {
       try mainContext.save()
    }
    catch {
       print(error)
    }
}

Is there any way by which we can synchronize mainContext & backgroundContext ? Please guide me it helps a lot to enhance my skill and solve the problem.

swift

core-data

nsmanagedobjectcontext

0 Answers

Your Answer

Accepted video resources