In SwiftData's modelContainer modifier, what do inMemory, isAutosaveEnabled, isUndoEnabled and onSetup control, and when do you pass your own ModelContainer instead?
answer
- three Bools and a closure
- defaults: false, true, false
- window undo manager on the main context
- Result<ModelContainer, any Error>
- modelContainer(_:) takes no options
basics
~20 sinMemory (default false) keeps the store off disk, isAutosaveEnabled (true) autosaves the main context, isUndoEnabled (false) binds the window's undo manager to it, and onSetup receives the container or the error. Pass your own instance when several scenes must share it.
solid answer
~40 sThe convenience form is `modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)`, on both `View` and `Scene`. `inMemory` defaults to `false`; `true` gives a store that never touches disk, which suits previews. `isAutosaveEnabled` defaults to `true`, so the main context saves on its own. `isUndoEnabled` defaults to `false`; with `true`, the window provides the system undo manager to SwiftData, which binds it to the main context, so shake and three-finger gestures undo changes saved there, and only there. `onSetup` receives a `Result<ModelContainer, any Error>`, the only place this form reports a failed load. When a journal window and a settings window must share one store, or code outside SwiftUI needs the container, I build one `ModelContainer` in the `App` and pass it to each scene with `modelContainer(_:)`, which takes no options; I configure its `mainContext` myself.
code
swift · 43 linesimport SwiftUI
import SwiftData
import os
private let logger = Logger(subsystem: "com.example.journal", category: "store")
// Convenience form: undo on, load failures reported in onSetup.
struct JournalScene: Scene {
var body: some Scene {
WindowGroup {
EntryListView()
}
.modelContainer(for: Entry.self, isUndoEnabled: true) { result in
if case .failure(let error) = result {
logger.error("Store failed to load: \(error)")
}
}
}
}
// Shared instance: both windows use one container and its main context.
@main
struct JournalApp: App {
let container: ModelContainer = {
do {
return try ModelContainer(for: Entry.self)
} catch {
fatalError("Could not open the journal store: \(error)")
}
}()
var body: some Scene {
WindowGroup {
EntryListView()
}
.modelContainer(container)
WindowGroup("Settings", id: "settings") {
SettingsView()
}
.modelContainer(container)
}
}go deeper
Know the three switches and their defaults: inMemory false, isAutosaveEnabled true, isUndoEnabled false.
Explain what each switch changes on the main context, what onSetup receives, and why modelContainer(_:) moves configuration onto the instance.
Show the judgment: share one instance across scenes, log onSetup failures, and state the undo boundary at the main context.
Decide where the app's single container is created and who may create others, so scenes, intents and importers agree on one store.
## Two shapes of one modifier SwiftData's SwiftUI layer declares the modifier twice, on `View` and on `Scene`, in two shapes: - **`modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)`**, the convenience form. You pass model types (one type or an array) and SwiftData builds the container for you. - **`modelContainer(_:)`**, which takes a `ModelContainer` you built yourself and has no other parameters. Both put the container's **main context**, a `ModelContext` bound to the main actor, into the environment, where views read it with `@Environment(\.modelContext)`. Both have been available since iOS 17. ## The four parameters | Parameter | Default | What it controls | |---|---|---| | `inMemory` | `false` | `true` keeps the whole store in memory; nothing is written to disk and the data is gone when the container goes away | | `isAutosaveEnabled` | `true` | Whether the main context saves pending changes on its own | | `isUndoEnabled` | `false` | Whether the scene's undo manager is attached to the main context | | `onSetup` | `{ _ in }` | A closure that receives `Result<ModelContainer, any Error>` once setup finishes | A few consequences worth saying out loud in an interview: - **Autosave** is why most SwiftData sample code never calls `save()`. Apple's `autosaveEnabled` documentation says such a context saves after changes to its inserted or registered models and at various points in the lifecycle of windows, scenes, views and sheets. Turning it off does not make the store read-only; it means your code must call `try modelContext.save()`. - **In-memory** is for previews and tests. It is not a cache in front of a disk store. - **`onSetup`** is the only hook the convenience form gives you when the store fails to open, for example after an incompatible schema change. Log it there; otherwise the failure is silent at the call site. ## Undo, precisely Apple's article on reverting data changes is specific about what `isUndoEnabled: true` does: 1. the app's window or window group provides the **system undo manager** to SwiftData; 2. SwiftData binds that manager to the container's **`mainContext`**; 3. each time changes are saved to the main context, SwiftData registers them with the undo manager, so people can undo with shake or the three-finger gesture on iPhone and iPad, or Edit > Undo on the Mac. The same article sets the limit: changes saved by **any other context**, such as a background context importing server data, are not covered. `DocumentGroup` apps get undo automatically. ## When to pass your own container The convenience form never hands the container to the rest of your code, apart from inside `onSetup`. Build the instance yourself and use `modelContainer(_:)` when: - **two scenes must share one container**, for example a journal `WindowGroup` and a settings window on iPad or Mac that should show the same entries through the same main context; - **code outside SwiftUI** needs the same container, such as a background importer or an App Intent; - you need a **`ModelConfiguration`** the convenience form cannot express (a specific store URL, an App Group, a read-only store); - you want to **decide what happens on failure** at launch rather than in a callback. ```swift let container = try ModelContainer(for: Entry.self) // in the App's body: WindowGroup { EntryListView() } .modelContainer(container) WindowGroup("Settings", id: "settings") { SettingsView() } .modelContainer(container) ``` Building the container in the `App` also moves the failure decision to launch, where it is visible: the sample above stops with a message, but an app could instead show a recovery screen or fall back to an in-memory store while it reports the problem. With the convenience form, the same failure arrives only in `onSetup`. Because `modelContainer(_:)` has no switches, the options move onto the instance: the main context already has autosave on, set `container.mainContext.autosaveEnabled = false` to change that, and assign an `UndoManager` to `container.mainContext.undoManager` if you want undo. ## Pitfalls - Expecting undo without passing `isUndoEnabled: true`; the default is `false`. - Using `inMemory: true` in the shipping scene after copying it from a preview: every launch starts empty. - Assuming undo reverts what a background context saved. - Ignoring `onSetup`, then debugging an empty list that is really a store that never opened.
- With modelContainer(_:) there is no isUndoEnabled parameter; how do you get undo?Assign an `UndoManager` to `container.mainContext.undoManager`; its default is `nil`. Apple's documentation also suggests setting it back to `nil` temporarily during expensive work such as a large import, to improve performance.
- Does isUndoEnabled let people undo what a background import saved?No. Apple's undo article says the setting covers changes saved to the main context only, not changes saved by other contexts such as one that stores data fetched from a server. Those writes need their own handling, or none.
- isUndoEnabled defaults to true, so undo works without any setup.
- Setting isAutosaveEnabled to false makes the store read-only.
- inMemory: true is a fast cache in front of the on-disk store.
- Undo also reverts changes a background context saved.
- modelContainer(_:) accepts the same autosave and undo switches.