I want to give the user the option to toggle iCloud sync on and off.
After researching for a while, I saw that one way one could achieve this is by setting the cloudKitContainerOptions
.
So I would set it to nil
if I don't want my database to be synched.
if(!UserDefaultsManager.shared.iCloudSyncOn) {
description.cloudKitContainerOptions = nil
}
That's all working fine, but I haven't found a way to do that during runtime.
I have tried to reinitialize my container when the user toggles, so that my container has different cloudKitContainerOptions
depending on the choice.
But this would only return me an error, when saving the context, saying: Thread 1: "Illegal attempt to establish a relationship 'addEntries' between objects in different contexts ...
, which I believe is due to the reinitialization.
I think I would have to pass down the newly created context to my whole view hierarchy, anything that caches the moc?
Here would be a simplified snipped of my CoreDataStack:
func setupContainer() -> NSPersistentContainer {
let container = NSPersistentCloudKitContainer(name: "...")
guard let description = container.persistentStoreDescriptions.first else { ... }
...
if(!UserDefaultsManager.shared.iCloudSyncOn) {
description.cloudKitContainerOptions = nil
}
container.loadPersistentStores(completionHandler: { ... })
...
return container
}
When the user toggles, setupContainer()
gets called.
Any help would be awesome, alternative ways are of course also welcomed!
Thanks.