I am trying to create a SwiftData app that has two separate SQLite data stores – one for data I will pre-create and distribute with my app and one for data the user will create when running the app – something like described in this article by Paul Hudson.
When I create and save items I get the error:
Failed to save after place creation: The model configuration used to open the store is incompatible with the one that was used to create the store.
For testing, I have two simple models:
@Model
class Person: Identifiable {
@Attribute(.unique) let id: UUID
let name: String
init(id: UUID = UUID(), name: String) {
self.id = id
self.name = name
}
}
@Model
class Place: Identifiable {
@Attribute(.unique) let id: UUID
let name: String
init(id: UUID = UUID(), name: String) {
self.id = id
self.name = name
}
}
I initialise SwiftData:
@main
struct MultiStoreApp: App {
var container: ModelContainer
init() {
let peopleStoreURL = URL.documentsDirectory.appending(path: "people.store")
let placeStoreURL = URL.documentsDirectory.appending(path: "places.store")
let peopleConfig = ModelConfiguration(schema: Schema([Person.self]), url: peopleStoreURL)
let placesConfig = ModelConfiguration(schema: Schema([Place.self]), url: placeStoreURL)
do {
self.container = try ModelContainer(for: Person.self, Place.self, configurations: peopleConfig, placesConfig)
} catch {
fatalError("Failed to create model container: (error.localizedDescription)")
}
}
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(container)
}
}
}
I then have a simple View that displays a list of all places and people, along with buttons to add people and places.
struct ContentView: View {
@Environment(.modelContext) private var modelContext
@Query var people: [Person]
@Query var places: [Place]
var body: some View {
NavigationStack {
List {
Section("People") {
ForEach(people) { person in
VStack(alignment: .leading) {
Text(person.name)
Text(person.id.uuidString)
.font(.caption)
}
}
}
Section("Places") {
ForEach(places) { place in
VStack(alignment: .leading) {
Text(place.name)
Text(place.id.uuidString)
.font(.caption)
}
}
}
}
GroupBox {
HStack {
Button(action: {
let person = Person(name: "Person (people.count)")
modelContext.insert(person)
do {
try modelContext.save()
} catch {
print("Failed to save after person creation: (error.localizedDescription)")
}
}, label: {
Text("Add Person")
})
Spacer()
Button(action: {
let place = Place(name: "Place (places.count)")
modelContext.insert(place)
do {
try modelContext.save()
} catch {
print("Failed to save after place creation: (error.localizedDescription)")
}
}, label: {
Text("Add Place")
})
}
}
.padding()
}
}
}
When I run the app on a clean simulator, I can add objects of one type, but as soon as I add an object of the other type I start getting errors.
Is what I’m trying to do possible?