我在应用程序中仅使用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保存而不会崩溃?
答案 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.
}