Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

No persistent stores error in SwiftData

I am following Apple's instruction to sync SwiftData with CloudKit. While initiating the ModelContainer, right after removing the store from Core Data, the error occurs:

FAULT: NSInternalInconsistencyException: This NSPersistentStoreCoordinator has no persistent stores (unknown).  It cannot perform a save operation.; (user info absent)

I've tried removing default.store and its related files/folders before creating the ModelContainer with FileManager but it does not resolve the issue. Isn't it supposed to create a new store when the ModelContainer is initialized? I don't understand why this error occurs. Error disappears when I comment out the #if DEBUG block.

Code:

import CoreData
import SwiftData
import SwiftUI

struct InitView: View {
    @Binding var modelContainer: ModelContainer?
    @Binding var isReady: Bool
    @State private var loadingDots = ""
    @State private var timer: Timer?

    var body: some View {
        VStack(spacing: 16) {
            Text("Loading\(loadingDots)")
                .font(.title2)
                .foregroundColor(.gray)
        }
        .padding()
        .onAppear {
            startAnimation()
            registerTransformers()
            let config = ModelConfiguration()
            let newContainer: ModelContainer

            do {
                #if DEBUG
                    // Use an autorelease pool to make sure Swift deallocates the persistent
                    // container before setting up the SwiftData stack.
                    try autoreleasepool {
                        let desc = NSPersistentStoreDescription(url: config.url)
                        let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.my-container-identifier")
                        desc.cloudKitContainerOptions = opts
                        // Load the store synchronously so it completes before initializing the
                        // CloudKit schema.
                        desc.shouldAddStoreAsynchronously = false
                        if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Page.self]) {
                            let container = NSPersistentCloudKitContainer(name: "Pages", managedObjectModel: mom)
                            container.persistentStoreDescriptions = [desc]
                            container.loadPersistentStores { _, err in
                                if let err {
                                    fatalError(err.localizedDescription)
                                }
                            }
                            // Initialize the CloudKit schema after the store finishes loading.
                            try container.initializeCloudKitSchema()
                            // Remove and unload the store from the persistent container.
                            if let store = container.persistentStoreCoordinator.persistentStores.first {
                                try container.persistentStoreCoordinator.remove(store)
                            }
                        }

//                        let fileManager = FileManager.default
//                        let sqliteURL = config.url
//                        let urls: [URL] = [
//                            sqliteURL,
//                            sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-shm"),
//                            sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-wal"),
//                            sqliteURL.deletingLastPathComponent().appendingPathComponent(".default_SUPPORT"),
//                            sqliteURL.deletingLastPathComponent().appendingPathComponent("default_ckAssets")
//                        ]
//                        for url in urls {
//                            try? fileManager.removeItem(at: url)
//                        }                    
                    }
                #endif
                newContainer = try ModelContainer(for: Page.self,
                                                  configurations: config) // ERROR!!!
            } catch {
                fatalError(error.localizedDescription)
            }

            modelContainer = newContainer
            isReady = true
        }
        .onDisappear {
            stopAnimation()
        }
    }

    private func startAnimation() {
        timer = Timer.scheduledTimer(
            withTimeInterval: 0.5,
            repeats: true
        ) { _ in
            updateLoadingDots()
        }
    }

    private func stopAnimation() {
        timer?.invalidate()
        timer = nil
    }

    private func updateLoadingDots() {
        if loadingDots.count > 2 {
            loadingDots = ""
        } else {
            loadingDots += "."
        }
    }
}
import CoreData
import SwiftData
import SwiftUI

@main
struct MyApp: App {
    @State private var modelContainer: ModelContainer?
    @State private var isReady: Bool = false

    var body: some Scene {
        WindowGroup {
            if isReady, let modelContainer = modelContainer {
                ContentView()
                    .modelContainer(modelContainer)
            } else {
                InitView(modelContainer: $modelContainer, isReady: $isReady)
            }
        }
    }
}

Initializing the ModelContainer in an onAppear of a view is too late, you need to do it directly in MyApp where yo declare the property itself.

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)

No persistent stores error in SwiftData
 
 
Q