NSPersistentCloudKitContainer: Data is gone when turning off iCloud in settings. Reappears when turning it on again.

I am using Core Data with CloudKit through NSPersistentCloudKitContainer.

When doing the following, all the data disappears:
  1. Start my app (iCloud enabled)

  2. Create some items in CoreData

  3. Quit the app

  4. Turn off iCloud for my app in the iPhone's Settings

  5. Start the app again

All the items added in step 2 are gone after this. When I turn iCloud on again, they reappear.

I read through the documentation, but this does not seem to be expected behaviour. Also, the demo app for this topic does not seem to have this issue. However, I am building my CoreData-stack in the same way as they do.

Searching on the web it seems that several people have the same issue. Did somebody resolve this?
I read that one strategy is to swap NSPersistentCloudKitContainer with NSPersistentContainer in case iCloud is turned off - but the demo-app doesn't do this and still keeps the data even when iCloud gets turned off. So there must be another way.

For reference, here's how I build my CoreData-stack (lazy var in a class):
Code Block
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentCloudKitContainer(name: "MyAppsName")
guard let storeDescription = container.persistentStoreDescriptions.first else {
fatalError("Could not load store description.")
}
storeDescription.type = NSSQLiteStoreType
storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores { (_, error) in
if let error = error as NSError? {
fatalError("Unresolved error when loading CoreData persistent stores: \(error), \(error.userInfo)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return container

Just to document it here: The issue seems to have resolved itself. I recently ported my App to iOS14 and was not able to reproduce the error again. I am not sure what changed, or if this was a bug, but it seems to work as expected now (data not disappearing).
NSPersistentCloudKitContainer: Data is gone when turning off iCloud in settings. Reappears when turning it on again.
 
 
Q