skip to content

In a SwiftUI app using SwiftData, how do you install the model container with the modelContainer modifier and reach the model context from a view?

level: juniorimportance: must knowfreq 72%

answer

  1. top of the scene or view tree
  2. modelContainer(for:) on the WindowGroup
  3. environment key path for the context
  4. same main-actor context @Query fetches through

basics

~10 s

Apply modelContainer(for: Entry.self) to the WindowGroup or the root view. SwiftData builds the container and puts its main-actor ModelContext into the environment, and any descendant reads it with @Environment(.modelContext) to insert and delete models.

solid answer

~40 s

I attach `.modelContainer(for: Entry.self)` to the `WindowGroup` in my `App`, or to the root view, so every view below inherits it. The modifier sets up the container from the model types I list (related types are pulled in through relationships) and puts the container's main-actor context into the environment. A view reads it with `@Environment(\.modelContext) private var modelContext` and calls `insert(_:)` and `delete(_:)`. There is no update call: the context tracks changes to the models it knows, and autosave writes them. `@Query` fetches through that same context. If I forget the modifier, the environment still holds a context, but Apple documents it as bound to an in-memory, schema-less container: inserts fail and fetches come back empty.

code

swift · 48 lines
swift
import SwiftUI
import SwiftData

@Model
final class Entry {
    var title: String
    var text: String
    var createdAt: Date

    init(title: String, text: String = "", createdAt: Date = .now) {
        self.title = title
        self.text = text
        self.createdAt = createdAt
    }
}

@main
struct JournalApp: App {
    var body: some Scene {
        WindowGroup {
            EntryListView()
        }
        .modelContainer(for: Entry.self)
    }
}

struct EntryListView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \Entry.createdAt, order: .reverse) private var entries: [Entry]

    var body: some View {
        List {
            ForEach(entries) { entry in
                Text(entry.title)
            }
            .onDelete { offsets in
                for index in offsets {
                    modelContext.delete(entries[index])
                }
            }
        }
        .toolbar {
            Button("New Entry") {
                modelContext.insert(Entry(title: "Untitled"))
            }
        }
    }
}

go deeper

for a junior

Recall the two lines: modelContainer(for:) on the WindowGroup, and @Environment(.modelContext) in the view that inserts or deletes.

for a middle

Explain that the modifier builds the container, publishes its main-actor context with autosave on, and that @Query fetches through that same environment context.

for a senior

Diagnose an empty list plus a failing insert as a view with no container above it, and know the default schema-less context Apple documents for that case.

for a principal

Set the team rule that one container is installed at the scene and views only read the environment context, so no screen quietly runs against a different store.

## What the modifier does SwiftData needs two objects before a view can show or save anything. A **`ModelContainer`** owns the schema (the list of `@Model` types) and the persistent store on disk. A **`ModelContext`** is the working area where you insert, delete and change model objects before they are written to that store. In a SwiftUI app you rarely build either by hand. The **`modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)`** modifier, declared on both `View` and `Scene` since iOS 17, does three things: - it builds a container for the model types you pass, one type or an array of root types; - it makes the container's **main context**, a context bound to the main actor, available in the SwiftUI environment; - it switches on autosave for that context unless you pass `isAutosaveEnabled: false`. Apple's documentation adds that you do not have to list every type: SwiftData follows a model's relationships and adds the destination types to the schema for you. List the root types, and use the array form when you have several unrelated roots. ## Where to put it Apple's guidance is to apply the modifier **at the very top of the view hierarchy**, so that every nested view inherits the configured environment. | Placement | What sees the container | Typical use | |---|---|---| | On the `WindowGroup` (scene modifier) | Every window that scene creates, and everything inside each window | The normal choice for an app | | On the root view inside the scene | That view and all of its descendants | When the root view is the natural boundary, for example in a preview | | On a view deep in the tree | Only that subtree | Rarely right; siblings outside it get no container | In a journaling app this is one line in the `App` struct: ```swift WindowGroup { EntryListView() } .modelContainer(for: Entry.self) ``` ## Reading the context in a view Any descendant reads the context through the environment with the key path `\.modelContext`: ```swift @Environment(\.modelContext) private var modelContext ``` With it the view can: 1. **insert** a new model with `modelContext.insert(entry)`, which starts tracking it; 2. **delete** a model with `modelContext.delete(entry)`; 3. **change** a model by simply assigning to its properties. `ModelContext` has no update method, because the context tracks every model it knows about; 4. **save** explicitly with `try modelContext.save()` when the code must not wait for autosave. `@Query` properties in the same views fetch through this same environment context, which is why a freshly inserted entry appears in the list without any extra wiring. Outside SwiftUI, the same main-actor context is reachable as `container.mainContext`. Two details help in reviews. First, the context is bound to the **main actor**, and so are SwiftUI views, so a button action can call `insert(_:)` directly without hopping actors. Second, every model exposes an optional, read-only **`modelContext`** property naming the context it is registered in; a child view that only receives an `Entry` can use `entry.modelContext` to reach the context the entry belongs to. Most code still reads the environment value, because it works before any model exists, for example to insert the first entry. ## What goes wrong without it The environment value `modelContext` is not optional, so a view compiles and runs even when no ancestor applied the modifier. Apple's `ModelContext` documentation says what it gets instead: - a context bound to an **in-memory, schema-less container**; - any **insert** into that context fails, and because `insert(_:)` is not a throwing method there is nothing to catch at the call site; - every **fetch** returns empty results, so a `@Query` list simply shows nothing. That combination, an empty list plus a failure on the first "New Entry" tap, is the classic symptom of a container installed on the wrong branch of the tree, or of a preview built without one. ## Rules of thumb 1. Install one container at the top: on the scene for an app, on the previewed view for a preview. 2. Read the context from the environment in views; do not construct a new `ModelContext` per view just to insert a row. 3. Let the context track edits; call `save()` only where you need the write to happen now. 4. Treat an empty `@Query` plus a failing insert as "no container above this view" before suspecting the data.

  • Do you have to list every model type in modelContainer(for:)?
    No. Apple's documentation says SwiftData traverses a model's relationships and includes the destination model types in the schema, so listing the root types is enough. The array form, such as `modelContainer(for: [Entry.self, Tag.self])`, is for several root types that no relationship connects.
  • Is the environment context the same object as the container's mainContext?
    Apple's documentation treats them as one: the environment context is described as the attached container's main-actor context, and the undo article tells you to retrieve `mainContext` in a view through the `modelContext` environment value. Code outside views therefore uses `container.mainContext` to reach the context the views use.
  • Can one part of the view tree use a different context?
    Yes. The `modelContext(_:)` modifier, on a view or a scene, replaces the environment context for that subtree, for example with a `ModelContext(container)` you created for a draft editor. Views inside read that context from the environment; everything outside keeps the main context.

  • SwiftData finds the @Model classes on its own, so the modifier is optional.
  • Every view that saves should create its own ModelContext.
  • Changing a model property needs a separate update call on the context.
  • Related model types must all be listed or they will not be stored.
  • An empty @Query list always means the store has no data.