ios – How can I use the same Model in SwiftData for two different ModelContainers?


I want to implement a trashcan for my app.
Using a very simple model I want to store to active items in one ModelContainer and the deleted ones in another.

In order to access the containers I wrote a singleton.

import SwiftData

class DataHolder {
    static let sharedInstance = DataHolder()
    
    let activeContainer:ModelContainer
    let trashContainer:ModelContainer

    
    private init() {
        
        let schema = Schema([Song.self])
        let storeURL = URL.documentsDirectory.appending(path: "active.sqlite")
        let config = ModelConfiguration(url: storeURL)
        let container = try! ModelContainer(for:schema, configurations: config)
        self.activeContainer = container;
        
        
        let schemaTrash = Schema([Song.self])
        let storeURLTrash = URL.documentsDirectory.appending(path: "trash.sqlite")
        let configTrash = ModelConfiguration(url: storeURLTrash)
        let containerTrash = try! ModelContainer(for:schemaTrash, configurations: configTrash)
        self.trashContainer = containerTrash;
        
        print("init datamodel")
       
    }
    
}

But when I try to save the active ContainerModel the App crashes.

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store."

I tried to add naming and change the storage location but nothing works. Is there a different approach to implement such a feature?

I’m aware of How can I have two stores of the same SwiftData model?. But the proposed solution doesn’t work in my case.

Edit:

The app crashed after inserting a new item:

Task {
        let newSong = Song();
        await DataHolder.sharedInstance.activeContainer.mainContext.insert(newSong)
       try! await DataHolder.sharedInstance.activeContainer.mainContext.save()
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img