SwiftData Multiple ModelConfigurations

A ModelContainer with two configurations for two seperate models with one set to isStoredInMemoryOnly:false and the other one isStoredInMemoryOnly:true crashes after insertion. Anyone git this to work?

import SwiftData

@main
struct RecipeBookApp: App {
    var container: ModelContainer
    init() {
        do {
            let config1 = ModelConfiguration(for: Recipe.self)
            let config2 = ModelConfiguration(for: Comment.self, isStoredInMemoryOnly: true)

            container = try ModelContainer(for: Recipe.self, Comment.self, configurations: config1, config2)
        } catch {
            fatalError("Failed to configure SwiftData container.")
        }
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .modelContainer(container)
        }
    }
}

struct ContentView: View {
    @Environment(\.modelContext) private var context

    @Query private var recipes: [Recipe]
    @Query private var comments: [Comment]

    var body: some View {
        VStack {
            Button("Insert") {
                context.insert(Recipe(name:"Test"))
                context.insert(Comment(name:"Test"))
            }
            List(recipes){ recipe in
                Text(recipe.name)
            }
            List(comments){ comment in
                Text(comment.name)
            }
        }
        .padding()
        .onAppear(){
            context.insert(Recipe(name:"Test"))
            context.insert(Comment(name:"Test"))
        }

    }
}

@Model
class Recipe {
    internal init(name:String ) {
        self.name = name
    }
    var id: UUID = UUID()
    var name: String = ""
}

@Model
class Comment {
    internal init(name:String ) {
        self.name = name
    }
    var id: UUID = UUID()
    var name: String = ""

}
Answered by DTS Engineer in 804683022

It seems that the SwiftData gets confused about the configuration name when there are multiple configurations. Explicitly specifying a name seems to fix the issue:

let config1 = ModelConfiguration("database1", schema: Schema([Recipe.self]) )
let config2 = ModelConfiguration("database2", schema: Schema([Comment.self]), isStoredInMemoryOnly: true)
container = try ModelContainer(for: Recipe.self, Comment.self, configurations: config1, config2)

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

It seems that the SwiftData gets confused about the configuration name when there are multiple configurations. Explicitly specifying a name seems to fix the issue:

let config1 = ModelConfiguration("database1", schema: Schema([Recipe.self]) )
let config2 = ModelConfiguration("database2", schema: Schema([Comment.self]), isStoredInMemoryOnly: true)
container = try ModelContainer(for: Recipe.self, Comment.self, configurations: config1, config2)

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Thank you, that seems to have fixed the issue.

SwiftData Multiple ModelConfigurations
 
 
Q