Search code examples
iosswiftcloudkit

Blindly append value to CloudKit record


Today I started looking into CloudKit and I'd like to know if there's a way to append values to fields marked as list.

The way that I do it now is:

  1. I query the record, get the current list of values.
  2. I locally add a value to the record
  3. I use the setValue(_: forKey:) method to completely write over the old value with the new value that I created in 2.
  4. I update the record saving it again

I was wondering if there is a way to "blindly" append a new value to a list field, without having to read the current value first and appending the new value on the client.

Thanks.


Solution

  • If you need to be able to append records without first getting the existing record, you might consider using a different record type and a CKReference.

    For example, let's pretend your current record type is Company and it has a field of employees that is of type String (List). You want to add more employees to that list without first knowing who else is in the list.

    You could make an Employees record type with a name field of type String and a company field of type CKReference. Then you can just create employees all you want and set their company reference and they'll be associated with their Company.

    You don't have to know anything else about who else is employed by the company, but you can still query CloudKit for all the employees associated with a particular company.

    All that said, it should be pretty easy to first get the record you are modifying, save the list of values to an array, append your new value, and save the array back to the CKRecord. :) Good luck!