尝试递归调用-save:在保存核心数据viewContext后保存CoreKit记录更改后的上下文

问题描述:

在我的应用中,当operation.recordChangedBlock {}里面的func fetchZoneChanges(database: CKDatabase, databaseTokenKey: String, zoneIDs: [CKRecordZoneID], completion: @escaping() -> Void)完成后,我使用从CloudKit接收到的新名称值更新Core Data数据库中的coreData记录。尝试递归调用-save:在保存核心数据viewContext后保存CoreKit记录更改后的上下文

错误试图递归调用-save:上下文中止当我试图挽救情境出现。

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记录更新时出现此错误?我试图将所有调用包装在主队列上运行,但这并没有帮助。

我也使用相同的方法updateCoreDataRecord()当用户改变在设备上核心数据记录,这将导致没有错误。我只在从operation.recordChangedBlock {}中接收到来自CloudKit的记录更改时收到此错误,其中我为记录创建了Core Data更新。

此方法是否在主线程上触发?如果没有,你需要将所有的核心数据工作移动到主线程,如果你在viewContext上工作,而不是保存。