In SwiftData, what is the difference between a ModelContainer and a ModelContext, and which one do you insert and delete models through?
answer
- two objects, two jobs
- schema and store vs workspace
- insert and delete live on one
- changes wait for a save
- container's mainContext is main-actor bound
basics
~20 sA ModelContainer owns the schema and the persistent store; a ModelContext is the in-memory workspace where you insert, delete, edit and save models. You call insert(:) and delete(:) on a context, often the container's mainContext.
solid answer
~40 s`ModelContainer` is the long-lived object that knows your app's schema and manages the store behind it: it does the actual reads and writes when a fetch runs or a context saves. `ModelContext` is where model objects live while you work with them: you call `insert(_:)` to register a new model, `delete(_:)` to mark one for removal, and simply set properties to edit one, because the context tracks changes on models it knows. Nothing reaches the store until the context saves, either through `save()` or autosave. Every container exposes `mainContext`, a context bound to the main actor, and you can create more with `ModelContext(container)`. An app has at least one container and usually several contexts.
code
swift · 23 linesimport SwiftData
import Foundation
@Model final class Inspection {
var siteName: String
var inspectedAt: Date
init(siteName: String, inspectedAt: Date) {
self.siteName = siteName
self.inspectedAt = inspectedAt
}
}
@MainActor
func recordVisit(in container: ModelContainer) throws {
let context = container.mainContext
let visit = Inspection(siteName: "Pump station 4", inspectedAt: .now)
context.insert(visit) // tracked, not yet on disk
visit.siteName = "Pump station 4B" // no update call needed
try context.save() // writes the insert and the edit
context.delete(visit) // removed at the next save
try context.save()
}go deeper
Recall the split: the container owns schema and store, the context is where you insert, edit, delete and save. Know that mainContext is the container's main-actor context.
Explain that edits are tracked automatically, that delete and insert are pending until a save, and that inserting a graph's root inserts its related models.
Show you know where each context may be used: mainContext belongs to the main actor, other work needs its own context on the same container, and unsaved changes live only in that context.
Frame the container as the app's single persistence boundary and contexts as units of work, and say how a team keeps that boundary consistent across features and tests.
## Two objects, two jobs SwiftData splits persistence into two objects, and many beginner bugs come from mixing up which one does what. | | `ModelContainer` | `ModelContext` | |---|---|---| | What it holds | The **schema** (your `@Model` types) and one or more store configurations | The model objects you are working with right now | | Lifetime | Usually one for the app's whole run | Many; short or long-lived | | What you call on it | Creation, `mainContext`, `configurations` | `insert(_:)`, `delete(_:)`, `fetch(_:)`, `save()`, `rollback()` | | Touches the store? | Yes: it performs reads and writes | Only through its container, when it fetches or saves | Apple's documentation describes the **container** as the object that "mediates between its associated model contexts and your app's underlying persistent storage": whenever a fetch runs or a context calls `save()`, the container performs the actual read or write. The **context** is the object that "enables you to fetch, insert, and delete models, and save any changes to disk". ## Creating them - `ModelContainer(for: Inspection.self)` builds a container for one model type; it **throws**, because opening or migrating a store can fail. - Passing no `ModelConfiguration` is allowed: SwiftData builds a default configuration from your app's entitlements and the type's default values. - Every container has a `mainContext` property, declared `@MainActor`, so you read it from main-actor code such as a view or a main-actor view model. - `ModelContext(container)` creates an additional context on the same container, for example for work that should not run on the main actor. ## Inserting, editing and deleting The context is the only place you change data: 1. **Insert**: create the model with its normal initializer, then call `context.insert(model)`. Until then the object is just a Swift instance the store knows nothing about. 2. **Edit**: set its properties. There is no update method, because the context tracks every change to models it has inserted or fetched. 3. **Delete**: call `context.delete(model)`. The documentation says SwiftData removes the model from the store **during the next save**; if the model was new and never saved, the context simply discards it. To delete many at once, `delete(model:where:includeSubclasses:)` takes a type and an optional predicate, and with no predicate it removes every model of that type. When models are related, you insert only the root of a new graph: the context recognises the relationships and inserts the related models with it, even when the graph mixes new and existing models. ## Nothing is on disk until a save Inserts, edits and deletes are **pending** in the context's memory. They reach the store when the context saves, either because you call `save()` or because the context's `autosaveEnabled` is on and it saves by itself. SwiftData switches autosave on for the container's `mainContext`; the context properties `hasChanges`, `insertedModelsArray`, `changedModelsArray` and `deletedModelsArray` show what is still pending. Exactly when autosave fires, and why a background context needs explicit saves, are their own topics; the point here is that the context, not the container, holds unsaved work. ## Where each object lives in an app - **One container, created early.** Most apps build a single `ModelContainer` at launch and share it; everything that reads or writes the same store goes through it. - **The main context for the UI.** Views and main-actor view models use `mainContext`, which is why it is the context SwiftUI code normally sees. - **More contexts for separate units of work.** An import, an export or a test creates its own context with `ModelContext(container)`, so its pending changes stay apart from the UI's until it saves. - **A fresh container per test.** Tests build their own, usually in memory, so no test sees another's rows. ## Mistakes interviewers listen for - Treating the container as the thing you insert into. `ModelContainer` has no `insert(_:)`; you always go through a context. - Expecting a newly created model object to be persistent because it was initialised. It is not tracked until a context inserts it. - Assuming `delete(_:)` removes the row immediately. It marks the model; the save writes the removal. - Inserting each child of a new object graph one by one. Inserting the root is enough. - Reaching for `mainContext` from a background task. It is declared `@MainActor`; work off the main actor uses a context of its own. Installing the container in a SwiftUI scene and reading the context from the environment are covered with SwiftData's SwiftUI integration; reading data with fetch descriptors and predicates is covered with querying and fetching.
- If a new Inspection owns several new Photo models through a relationship, do you insert each one?No. Insert the root of the graph and the context recognises the relationships and inserts the related models too. Apple's documentation says this holds even when the graph mixes new and existing models, so one `insert(_:)` on the inspection is enough.
- What happens if you call delete(_:) on a model you inserted but never saved?The context discards it. `delete(_:)` normally removes the model from the store at the next save, but a new, unsaved model has nothing in the store, so the context just drops the pending insert and nothing is ever written.
- How many containers and contexts does a typical app have?At least one container, often exactly one for the app's store, shared by everything. Contexts are cheap and plentiful: the container's `mainContext` serves main-actor code such as views, and work off the main actor creates its own context on the same container.
The container is the archive building with its filing rules; a context is a clerk's desk. You draft, correct and strike out papers on the desk, and nothing changes in the archive until the clerk files the batch.
- You insert models into the ModelContainer directly.
- A model is saved as soon as you create it with its initializer.
- You must call an update method on the context after changing a property.
- delete(_:) removes the row from the store immediately.
- Every model in a new related graph needs its own insert(_:) call.
- The container's mainContext can be used from any thread.