gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:35:06 25 4
gpt4 key购买 nike

我在我的应用程序中只使用了 Core Data 的主上下文。我知道 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 主上下文保存?

最佳答案

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

关于ios - 我可以从后台线程调用或运行 Core Data Main Context (viewContext) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com