首页 > 解决方案 > 我可以从后台线程调用或运行 Core Data Main Context (viewContext) 吗?

问题描述

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

    //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 保存而不会崩溃?

标签: iosswiftcore-data

解决方案


使用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. 
}

推荐阅读