I'm confused about how to best save an object that contains an array of other objects in CloudKit.
Say I have a todo list app, which has different collections of items. How would I go about saving/fetching a whole collection of items?
Would I have a Record type of Collection, which would have a String Attribute called "Name", and then a Reference List Attribute called "Items"?
I know that the Record type of Item needs to have a Reference Attribute called "Collection", because of how CloudKit references from a child object to its parent.
I have managed to save a Collection without any instances of Item with the following code
func addCollection(collection: Collection!, completion: (error: NSError!) -> ()) {
if collection == nil
return
}
let collectionRecord = CKRecord(recordType: "Collection")
CollectionRecord.setObject(collection.name, forKey: "Name")
privateDB.saveRecord(collectionRecord) {
record, error in
dispatch_async(dispatch_get_main_queue()) {
completion(error: error)
}
}
}
The other option is when saving a Collection, to loop through all instances of Item and also save those individually, their Reference Attribute to Collection making the connection on the CloudKit side, but this seems like way too many network calls.
For the
Itemrecords you need aCKReferenceto theCollection. You will then be able to set aCKReferenceActionon that. You don't need to create aCKReferencelist on theCollection.Having a list of CKReference objects is only an option when you are planning to use
CKReferenceAction.NoneWhich would mean that there is not a strict relation between the two recordTypesIf you have a
Collectionobject, then you can easily query theItemrecordType using a predicate that Checks if the CKReference is that of theCollection.Usually there is no need to save multiple records. Once you have created a Collection with Items the relation can remain unchanged. If you do need to change multiple records, then you could try using the
CKModifyRecordsOperationwhich has support for saving multiple items in one action.When linking existing
ItemrecordTypes to aCollection, you do need to save eachItembecause it has a CKReference to theCollecion. TheItemhas changed, so it must be saved.