Caching CKRecords

It’s not possible to update an existing record in CloudKit without having saved specific data from a CKRecord given to you by CloudKit. You can’t simply create a new CKRecordID and use the last changeToken and create a CKRecord yourself usingt those. If you do, CloudKit thinks you’re tryingt o create a brand new record. It will given an error if the record name already exists in that zone.

So you must either 

  1. fetch a record, change data in the CKRecord you got, and give that CKRecord to the modify operation,


  1. save the record in whole or part, change data in that CKRecord, and give that CKRecord to the modify operation. 

Method is 2 is necessary if you’re coordinating data across devices, because then the modify will correctly fail if another device modified the record since your last caching of it. You can save cache size by saving only the necessary parts of the CKRecord.

Caching CKRecord

The canonical way to cache the salient record data is CKRecord.encodeSystemFields. The prescribed method is to archive using an NSCoder, however JSONEncoder does not implement that.

Further reading