I'm working to refactor a somewhat clunky iterative save loop for CloudKit to use CKModifyRecordsOperation and bulk save records.
I have a Course, which has 1+ Weeks, each which has 1+ Lessons. Previously I'd create the Course in CloudKit, then create the Weeks, then the Lessons and circle back to update the Weeks with the Lesson references once created. And also fetch and save the Course record with the references to the Weeks once Weeks were created.
I've refactored to create all (Course, Week and Lesson) records locally, with the relevant references set up. E.g., course["weeks"] contains the record references for each week I've created locally, for example:
Is the correct protocol here actually my original approach?
Or is there something I'm missing?
Original approach:
CKModifyRecordsOperation code:
I have a Course, which has 1+ Weeks, each which has 1+ Lessons. Previously I'd create the Course in CloudKit, then create the Weeks, then the Lessons and circle back to update the Weeks with the Lesson references once created. And also fetch and save the Course record with the references to the Weeks once Weeks were created.
I've refactored to create all (Course, Week and Lesson) records locally, with the relevant references set up. E.g., course["weeks"] contains the record references for each week I've created locally, for example:
Code Block course["weeks"] = getWeekRefsForCourse(for: allWeeks) func getWeekRefsForCourse(for allWeeks: [CKRecord]) -> [CKRecord.Reference] { var weekRefsArray: [CKRecord.Reference] = [] for each in allWeeks { let weekRef = CKRecord.Reference(record: each, action: .deleteSelf) weekRefsArray.append(weekRef) return weekRefsArray }
The issue is when I go to save, the error I get back is:This suggests that I've got a record referring to itself, but I've gone record by record and I I can't see anything. The Weeks reference the Course and the Lessons, but not themselves, etc. So my only theory is that because I'm trying to save items that refer to other items that haven't yet been created, what I'm trying to do isn't possible.Invalid list of records: Cycle detected in record graph
Is the correct protocol here actually my original approach?
Or is there something I'm missing?
Original approach:
Save Course
Save Week
Save Lessons
Update Weeks with Lesson references
Update Course with Week references
CKModifyRecordsOperation code:
Code Block let bulkSaveQueryOp = CKModifyRecordsOperation() bulkSaveQueryOp.recordsToSave = [courseRecord] bulkSaveQueryOp.recordsToSave?.append(contentsOf: weeks) bulkSaveQueryOp.recordsToSave?.append(contentsOf: lessons) //note I've confirmed I have the correct number of records bulkSaveQueryOp.modifyRecordsCompletionBlock = { records, recordIDs, error in if let error = error as? CKError { log.error(error) } else { // success } } CKContainer.default().publicCloudDatabase.add(bulkSaveQueryOp)