【发布时间】:2018-03-05 14:55:06
【问题描述】:
在我的应用程序中,当 operation.recordChangedBlock {} 内的 func fetchZoneChanges(database: CKDatabase, databaseTokenKey: String, zoneIDs: [CKRecordZoneID], completion: @escaping () -> Void) 完成后,我使用从 CloudKit 收到的新名称值更新我的 Core Data 数据库中的 coreData 记录。
当我尝试保存上下文时出现错误尝试递归调用 -save: on the context aborted。
func updateCoreDataRecord(editedRecord: Record, newName: String, handleComplete_RecordEditedInCoreData:(()->())) {
let record_RecordID = editedRecord.recordID!
let request: NSFetchRequest<Record> = Record.fetchRequest()
request.predicate = NSPredicate(format: "recordID = %@", record_RecordID)
do {
let results = try self.viewContext?.fetch(request)
if results?.count == 1 {
let recordToUpdate = results![0]
recordToUpdate.setValue(newName, forKey: "name")
DispatchQueue.main.async { // Here I receive the error when editing goes from CloudKit
self.saveViewContext()
}
handleComplete_RecordEditedInCoreData()
}
} catch {
print(error)
}
}
以下是其他相关功能:
func saveViewContext() {
let context = self.getViewContext()
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func getViewContext() -> NSManagedObjectContext {
return self.persistentContainer.viewContext
}
我的应用程序中的所有viewContext 调用都是在主线程中进行的。我想这可能会导致错误。
错误导致saveViewContext方法。我不确定,但我认为这可能是一个并发问题,但我不知道如何解决。
在获取 CloudKit Record 更新时,我应该如何重写我的代码以避免此错误?我试图包装所有调用以在主队列上运行,但这没有帮助。
我也在使用相同的updateCoreDataRecord() 方法,当用户更改设备上的 Core Data 记录并且这不会导致错误。当我在 operation.recordChangedBlock {} 中接收来自 CloudKit 的记录更改时,我只会收到此错误,我在其中为记录进行核心数据更新。
【问题讨论】:
标签: ios swift core-data cloudkit nsmanagedobjectcontext