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

时间:2017-04-10 01:33:22

标签: ios swift multithreading core-data nsfetchrequest

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

Wich 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 :)

1 个答案:

答案 0 :(得分:0)

托管对象上下文通常被称为“便笺簿”。您对其所做的任何更改仅在内存中,直到您保存()它们。即使在保存之后,如果您的上下文具有父上下文,那么这些更改仍然可能无法访问实际数据库,直到 父上下文保存等等。

所以是的,在多个线程上操作Core Data是导致问题的原因。通常的解决方案是使用单个后台上下文来持久保存从服务器返回的更改,以便这些更改相互序列化。