Create Reference List Pointing to Multiple CKRecords in CloudKit

993 views Asked by At

Swift 3.1, Xcode 8.3.3

I have a record type in CloudKit called Aircraft and it has a field called fieldValues that is of type Reference List.

In my code, I have an aircraft CKRecord and several fieldValue CKRecords that are children of the aircraft.

How do I put all those fieldValue records into the aircraft's reference list?

Creating a CKReference appears to only allow a single record in it:

let reference = CKReference(record: fieldValueRecord, action: .deleteSelf)

But I'm trying to connect many fieldValues to a single aircraft. Any ideas?

1

There are 1 answers

0
Clifton Labrum On

Swift 3.1, Xcode 8.3.3

After some trial and error, I finally figured it out. It goes something like this:

//Parent record (Aircraft)
let recordAircraft = CKRecord(recordType: "Aircraft", recordID: ...)

//Add child references (FieldValue). As far as I know, the child records must have already been created and sent to CloudKit
var fieldValueReferences = [CKReference]()

for fieldValue in fieldValues{
  let ref = CKReference(record: fieldValue, action: .deleteSelf)
  fieldValueReferences.append(ref)
}

//Assign the array of references to the key that represents your Reference List field
recordAircraft["fieldValues"] = fieldValueReferences as CKRecordValue

I hope that helps someone else.