我可以从后台线程调用或运行Core Data Main Context(viewContext)吗?

时间:2019-04-10 11:34:45

标签: ios swift core-data

我在应用程序中仅使用Core Data的Main Context。我知道Main Context只能运行Main线程。 但是,当我从后台线程内部更新主上下文时,不会遇到任何崩溃。

    //Cloudkit operation
 let zoneOperation = CKFetchRecordZoneChangesOperation(recordZoneIDs: zonesIDs, optionsByRecordZoneID: [zonesIDs[0]: options])

 zoneOperation.recordChangedBlock = { (record) in

// This is background thread
 print("Record has changed")
    let date = record["date"] as! Date

//Fetching Managed Object Context from Coredata (Main Context)
if let migraine = migraine(OnDate: date, inContext: self.persistentContainer.viewContext) {
migraine.date = date
saveData(inContext: self.persistentContainer.viewContext)
}
}

如何在后台线程内执行Coredata Main Context保存而不会崩溃?

1 个答案:

答案 0 :(得分:2)

使用perform(_:)performAndWait(_:)确保对上下文的更改在上下文所属的线程上发生。

persistentContainer.viewContext.performAndWait { 
  self.saveData(inContext: persistentContainer.viewContext)
}

您也可以使用类似的方法

persistentContainer.performBackgroundTask { context in
  // Do stuff on this context and arrange for the changes
  // to be merged back to the view context. 
}