SwiftData: Solving data persistence on disk
This is the first part of a series called Learning Swift where I build an app for sailors from scratch.
After watching the WWDC2023 presentation of SwiftData, I decided to try it.
I wanted to persist my model’s data between relaunches but I couldn’t make it work. The autosave feature didn’t work as expected. Based on the documentation, this feature is activated by default.
After a few hours, I discovered that the option isAutosaveEnabled
of a ModelContainer
is only set to true when you don’t instance a ModelContainer yourself.
// Here I create a ModelContainer for the Boat model.
@MainActor
let container: ModelContainer = {
do {
let container = try ModelContainer(
for: Boat.self, ModelConfiguration()
)
return container
} catch {
fatalError("Failed to create container")
}
}()
// And I pass it to my view
@main
struct OnshoreApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(container)
}
}
}
In this case, the isAutosaveEnabled
is set to false.
But if I write this:
@main
struct OnshoreApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(for: Boat.self)
}
}
}
Now the isAutosaveEnabled
is set to true!
I only found out by watching Dive deeper into SwiftData (timestamps 11:00).