What's the best approach to prefill Core Data store when using NSPersistentCloudKitContainer?

Hello,


I'm parsing objects from a JSON file and store them into my Core Data store.

I'm using

NSPersistentCloudKitContainer
and when I'm running the app on a different device, it also parses the JSON file and adds objects to Core Data. That results in duplicate objects.


How can I check that an entity already exists remotely ?

Loading some objects from a local JSON file for initialisation sounds fine to me.


An entity with its attributes, relationships etc. describes your object. It is defined in your app and should be there.
It sounds like you rather want to check if there are already saved objects.

You can simply check if there are any saved objects in your store and only add your example objects if the store is empty.


Or, assuming there is some kind of identifier which makes your object unique, you can set the constraints of your entity to this attribute.
You should also set a merge policy then to specify the required behaviour when another object with the same identifier shows up.

How can I check that an entity already exists remotely ?

In theory you could write some CloudKit code to execute a CKQueryOperation that checks for your seed content. But that won't handle the race between a device exporting the data and another device launching the app and parsing the json file.

You can also check if records exist in the local store using NSFetchRequest. However for the same reason that won't prevent you from inserting duplicate records on multiple devices if they haven't synced with the CloudKit server yet.

There are a number of approaches to "seeding" your application store with content in a reliable way:
  1. Don't sync the seed content, instead use an un-synced store to hold the data from the JSON file and a synced store to hold user data

  2. Unique the seed content on each device as it is updated by NSPersistentCloudKitContainer

Unfortunately NSPersistentCloudKitContainer does not support unique constraints yet, you can file a feedback request for that though.
What's the best approach to prefill Core Data store when using NSPersistentCloudKitContainer?
 
 
Q