ios - 我可以从后台线程调用或运行 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 保存而不会崩溃?
解决方案
使用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.
}
推荐阅读
- user-interface - 从 Unity 中的 MultiFloatField 中检索值
- mysql - 当您连接 2 个具有相同架构的表并检查除一个以外的所有字段是否相等时,如何避免在 SQL 中编写冗长的 where 子句?
- string - 检查字符串是否在静态编译时集中的最快方法是什么?
- python - 在 Django 的 ORM 中只使用 `foreign_key=` 和 `foreign_key_id=` 有什么区别吗?
- rust - 自动转发操作,同时保持结果包装
- node.js - 是否可以在 Node.js 中检测代码是否执行其他脚本/文件
- javascript - JavaScript画布来回移动矩形
- android - 为什么Android中不同片段中的多个SupportMapFragment重叠?
- socrata - Socrata API - 如何将查询中的空数据字段替换为结果数组中的空字符串
- perforce - 在 LAN 上连接到 Perforce 个人服务器