Is it possible to unload/change the PersistenceStore in a SwiftUI App during runtime

Hi,

I want to activate/deactivate the CloudKit Sync during App runtime in a user settings view. Basically this works fine. Every time I toggle between the NSPersistentContainer and the NSPersistentCloudKitContainer, I increase the persistence.persistenceContainerReloaded attribute and the whole view hierarchy will be reloaded. Thus all changes are passed through the whole app.

During the reload phase I have to load a new persistence store by container.loadPersistentStores(...). Unfortunately, I cannot remove the old persistence store before loading the new one. The app crashes immediately, because the store and viewContext is still in use. Therefore, I just create a new one and trigger the reload. Afterwards every view is using the new viewContext. But somewhere in the background there is still the old persistence store with CloudKit Sync active and pushes every local change to the cloud. Changes on the cloud from other devices are not received anymore.

Does someone has any idea, how to correctly unload a PersistentStore (replace NSPersistentCloudKitContainer by NSPersistentContainer) in a SwiftUI based app?

@main
struct TargetShooterApp: App {
    @StateObject var persistence: Persistence = Persistence.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, persistence.container.viewContext)
                .id(persistence.persistenceContainerReloaded)
        }
    }
}
Post not yet marked as solved Up vote post of Morpheus78 Down vote post of Morpheus78
310 views

Replies

Hello! Have you managed to find any solution to this? It seems there is no working solution for CloudKit sync in SwiftUI app during runtime.