CoreData/SwiftData persistent history error after adding additional models

I'm trying to add two more data models SectionsSD andArticles SD to an existing project using SwiftData where I had one model and am running into a variety of CoreData errors when I try to run my app. I am running Xcode 15.2 and the latest iOS simulator at iOS 17.2

Here is my container

let container: ModelContainer = {
        let schema = Schema([
            LocationData.self,
            SectionsSD.self,
            ArticlesSD.self
        ])
        let container = try! ModelContainer(for: schema, configurations: [])
        return container
    }()

After I add these two models I get the following errors and I can't load data into the SectionsSD and ArticlesSD models. If I comment out my LocataionData model that works w/o error or if I run just LocationData it runs without error but run all together and I get the following errors in the log:

error: Error: Persistent History (11) has to be truncated due to the following entities being removed: (
    SectionsSD,
    ArticlesSD
)
CoreData: error: Error: Persistent History (11) has to be truncated due to the following entities being removed: (
    SectionsSD,
    ArticlesSD
)
warning: Warning: Dropping Indexes for Persistent History
CoreData: warning: Warning: Dropping Indexes for Persistent History
warning: Warning: Dropping Transactions prior to 11 for Persistent History
CoreData: warning: Warning: Dropping Transactions prior to 11 for Persistent History
warning: Warning: Dropping Changes prior to TransactionID 11 for Persistent History

Any advice here would be appreciated. These are initial models so migration is not really a need yet. Seems to just **** if you add more models.

Replies

The best info I can find is to delete the the persistence history... maybe. However, since this is created in SwiftData there is no ".xcdatamodeld" and thus no way to call up and delete that persistence history. I've tried using the following to get at it but the historyFetchRequest fails because it is looking for the name of the coredata model.

 func fetchAndClearPersistentHistory() {
        let context = container.newBackgroundContext() // Using a background context for operations
        let historyFetchRequest = NSPersistentHistoryTransaction.fetchRequest!
CoreData: error:  Failed to load model named MySampleApp
ZenTrac/CoreDataStackClass.swift:31: Fatal error: Unexpectedly found nil while unwrapping an Optional value
  • Long story short is you have to make the model accessible across the app for both views and for swift access. While I was fine through views it was when I was trying to update the SwiftData via some functions that I ran into problems. Making the model container shared across the app solved the problem.

Add a Comment

@OpExNetworks I have a similar issue. What did you do for 'Making the model container shared across the app solved the problem' ? Thank you.

created this variable:

// Define a global access point for the sharedModelContainer in a way that it can be accessed outside of SwiftUI views
class AppEnvironment {
    static var sharedModelContainer: ModelContainer!
}

Added the following to my @Main app:

    init() {
        LogEvent.print(module: "\(AppValues.appName)App.init()", message: "App startup...")

        // TODO: Do stuff at startup
        LogEvent.print(module: "\(AppValues.appName)App.init()", message: "Settings..." + printUserSettings(description: "Settings", indent: "  "))
                
        NetworkStatus.shared.startMonitoring()
        
        AppEnvironment.sharedModelContainer = initializeModelContainer()
        
        // Set any default settings here
        UserSettings.init().userMode = .development
        
        LogEvent.print(module: "\(AppValues.appName).init()", message: "App startup...")

    }
    
    // Setup the shared model container so the data can be access across the app
    //
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            GpsJournalSD.self,
            TripSummariesSD.self,
            TripJournalSD.self,
            SectionsSD.self,
            ArticlesSD.self
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()
    
    private func initializeModelContainer() -> ModelContainer {
        let schema = Schema([
            GpsJournalSD.self,
            TripSummariesSD.self,
            TripJournalSD.self,
            SectionsSD.self,
            ArticlesSD.self
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
        
        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }
    
    var body: some Scene {
        WindowGroup {
            MasterView()
                .environmentObject(UserSettings())
            
        }
        .modelContainer(sharedModelContainer)

...

for access in a function:

    
    do {
        guard let container = AppEnvironment.sharedModelContainer else {
            LogEvent.print(module: "processTrips()", message: "container is nil")
            return
        }
        let context = ModelContext(container)
...

for access in my view

    @Environment(\.modelContext) private var modelContext
...