How to enable or disable autosave for a ModelContext
How to enable or disable autosave for a ModelContext 관련
Updated for Xcode 16
SwiftUI provides a built-in model context called the main context, and it has autosave enabled – SwiftData will automatically save your changes but you can also create a custom model context without that.
If you want to do this across your whole app – if you want your primary model context to have save disabled – then you would modify your App
struct to this:
WindowGroup {
ContentView()
}
.modelContainer(for: User.self, isAutosaveEnabled: false)
To be clear
This means you’re responsible for calling save()
on your model context manually.
If you’re making a new context by hand, autosave is usually automatically disabled. You can enable it by adjust its autosaveEnabled
Boolean like this:
let newContext = ModelContext(container)
print(newContext.autosaveEnabled)
newContext.autosaveEnabled = true
Tips
It's not specified exactly when autosave is enabled for new contexts, so I'd recommend setting the value explicitly to avoid problems.