Post

Replies

Boosts

Views

Activity

Reply to No persistent stores error in SwiftData
The crash you’re seeing— FAULT: NSInternalInconsistencyException: This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation. (Apple Developer) —happens because by the time your onAppear runs, the debug block has already loaded and then removed the only store from the underlying NSPersistentCloudKitContainer. When you immediately call newContainer = try ModelContainer(for: Page.self, configurations: config) SwiftData’s internal coordinator finds no stores to save into and throws. The fix is to perform both the CloudKit‐schema initialization and your ModelContainer setup early, in your App struct (or in its init), rather than inside an onAppear. That way SwiftData creates its SQLite store after you’ve torn down the temporary CloudKit container, so it can recreate a fresh store. For example: @main struct MyApp: App { // 1) Build your debug store, initializeCloudKitSchema, remove it… // 2) Then immediately create the SwiftData ModelContainer private var modelContainer: ModelContainer = { #if DEBUG try! autoreleasepool { let config = ModelConfiguration() let desc = NSPersistentStoreDescription(url: config.url) // …set cloudKitContainerOptions, load stores synchronously… let container = NSPersistentCloudKitContainer( name: "Pages", managedObjectModel: mom ) container.persistentStoreDescriptions = [desc] container.loadPersistentStores { _, err in if let err { fatalError(err.localizedDescription) } } try container.initializeCloudKitSchema() if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } #endif return try! ModelContainer( for: Page.self, configurations: ModelConfiguration() ) }() var body: some Scene { WindowGroup { ContentView() .modelContainer(modelContainer) } } } That change ensures the coordinator always has a store by the time SwiftData’s ModelContainer initializer runs, eliminating the “no persistent stores” error. (Apple Developer)
May ’25