Jopz
Jopz

Reputation: 121

How to fetch unsaved data from CoreData from background thread in Swift?

I created a NSManagedObjectContext using:

lazy var managedObjectContext: NSManagedObjectContext = {
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

Then I make an API call with AlamoFire and in the callback I try to save the parent:

let objectDescription = NSEntityDescription.entity(forEntityName: "Parent", in: managedObjectContext)
var managedObject = NSManagedObject(entity: objectDescription!, insertInto: managedObjectContext) as? Parent

Which completes successfully (yay!)

Then I make an API call to get their children and in the callback I try to fetch the parents in order to link them:

let fetchRequest:NSFetchRequest<Parent> = NSFetchRequest<Parent>(entityName: "Parent")
fetchRequest.includesPendingChanges = true
let result = try managedObjectContext.fetch(fetchRequest)

Now I'm getting result.count = 0

Those two CoreData operations are occurring in different threads, and I feel this is the problem... Is it really? How do I solve this?

Thank you very much

Upvotes: 1

Views: 619

Answers (1)

Dave Weston
Dave Weston

Reputation: 6635

The managed object context is often referred to as a "scratch pad". Any changes you make to it are only in memory, until you save() them. Even after a save, if your context has a parent context, those changes still may not hit the actual DB, until that parent context saves, etc.

So yes, manipulating Core Data on multiple threads is what is causing your issue. The usual solution is to use a single background context to persist changes you get back from a server, so that those changes are serialized against one another.

Upvotes: 0

Related Questions