Search code examples
swiftcore-datacloudkitnspersistentcloudkitcontainer

CloudKit integration requires that all attributes be optional, or have a default value set. Does not detect default UUID value


I am writing an app which is backed by CoreData with CloudKit integration. I have a few non-optional things in my model and provided default values for them (a few numbers which logically would default to 0 anyway).

I also have an id associated with each object which I am storing as a UUID type in core data. Xcode would not compile the project until I provided a default value for this UUID (as it is declared as non-optional).

After some looking around online I followed the advice here.

The ID with a default value provided

This now builds however when running the app in a simulator I hit a fatalError when initialising my NSPersistentCloudKitContainer

The error occurs whilst loading the persistent stores in the following code:

init(inMemory: Bool = false) {
        container = NSPersistentCloudKitContainer(name: "FuelTrackr")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)") // error occurs here
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    }

The error states: CloudKit integration requires that all attributes be optional, or have a default value set. The following attributes are marked non-optional but do not have a default value: FuelEntryCD: id, VehicleCD: id

Both the FuelEntryCD and VehicleCD types have had their id attribute set with the default value as shown above.

Is there any way to fix this error without setting the properties to be optional? And if setting the ids to be optional is the only way to fix the problem, is this necessarily a bad thing?

Thanks

EDIT: Just to add I have also added awakeFromInsert which assigns a default UUID() value also but this seems to have no effect


Solution

  • Default values for UUID attributes are broken in Core Data (FB10592334, if anyone from Apple sees this). You can add a default in the model but it has no effect when the app runs. You're doing it right but the framework has a bug that prevents it from working properly.

    If you store the string representation of the UUID, it should work as expected.