skip to content

In SwiftData, when does a ModelContext write changes to the store, and what do autosaveEnabled, save(), hasChanges and rollback() each control?

level: middleimportance: should knowfreq 55%

answer

  1. pending until a save
  2. autosave is a context property
  3. only mainContext is switched on
  4. rollback restores the last committed state
  5. check before you save

basics

~20 s

A ModelContext keeps changes in memory until it saves: you call save(), or autosaveEnabled saves for you. Autosave defaults to false and SwiftData turns it on for mainContext; hasChanges reports pending work and rollback() discards it.

solid answer

~40 s

Inserts, edits and deletes stay pending in the context until a save writes them through the container. `save()` does it explicitly and throws on failure; Apple's documentation suggests checking `hasChanges` first so SwiftData does no unnecessary work. `autosaveEnabled` makes the context call `save()` itself after changes to its models and at lifecycle points of windows, scenes, views and sheets. Its documented default is `false`, and SwiftData sets it to `true` for the container's `mainContext`, so a context you create yourself, such as one inside a `@ModelActor`, should save explicitly. `rollback()` discards pending inserts and deletes, restores changed models to their last committed state and empties the undo stack, which means it cannot undo an edit that autosave has already committed. `transaction(block:)` runs a closure and then saves.

code

swift · 28 lines
swift
import SwiftData
import Foundation

@Model final class Inspection {
    var siteName: String
    var notes: String
    init(siteName: String, notes: String = "") {
        self.siteName = siteName
        self.notes = notes
    }
}

func recordAudit(container: ModelContainer) throws {
    let context = ModelContext(container)
    context.autosaveEnabled = false         // say it; don't rely on a default

    let draft = Inspection(siteName: "Substation 9")
    context.insert(draft)                   // hasChanges is now true
    context.rollback()                      // the insert is discarded

    try context.transaction {
        context.insert(Inspection(siteName: "Substation 10"))
    }                                       // saved when the block returns

    if context.hasChanges {
        try context.save()
    }
}

go deeper

for a junior

Remember that changes are pending until a save, that save() throws, and that the main context autosaves.

for a middle

Explain the documented autosave default and which context SwiftData switches on, what rollback() restores, and why hasChanges is checked before save().

for a senior

Spot lost background work with no save, Cancel buttons that rely on rollback() after autosave, and swallowed save errors, and say what you would change in review.

for a principal

Decide where a team relies on autosave and where it requires explicit saves, and how that rule is reviewed and tested.

## Pending until saved A `ModelContext` is a unit of work. When you insert a model, set its properties or delete it, the change exists **only in that context's memory**. It reaches the store when the context **saves**, and the container then performs the write. Until then other contexts on the same container cannot fetch it, and a crash loses it. The context gives you four controls over that lifecycle: | Member | What it does | |---|---| | `save()` | Writes pending inserts, changes and deletes; `throws` on failure | | `autosaveEnabled` | When `true`, the context calls `save()` on its own | | `hasChanges` | `true` while anything is pending | | `rollback()` | Discards pending work and restores changed models | `transaction(block:)` combines a closure and a save: it runs the block, then writes whatever is pending. ## Autosave: who has it and what it promises Apple's documentation for `autosaveEnabled` says two things: - When `true`, the context calls `save()` after you change any inserted or registered model, and also at various times during the lifecycle of windows, scenes, views and sheets. - The **default is `false`**, and SwiftData **sets it to `true` for the container's `mainContext`**. So the context SwiftUI code normally uses saves by itself, and `mainContext` is the only context documented to autosave. For a context you create with `ModelContext(container)`, including the one a `@ModelActor` makes, set `autosaveEnabled` explicitly instead of inferring it from a default, and call `save()` where you need the data durable. Two consequences follow: 1. **Work in a background context is lost without a save.** Ten thousand inserts in a context that does not autosave never reach the store if the code forgets `save()`. 2. **Autosave promises that a save happens, not when.** The documentation does not give a timing. Where data must survive, such as after a user taps Submit on an inspection report, call `save()` yourself rather than hoping the next lifecycle event comes first. ## save() and hasChanges `save()` throws, so a failed write is an error you must handle. Apple's documentation adds an **Important** note: use `hasChanges` to see whether there is anything to save before calling `save()`, otherwise SwiftData may perform unnecessary work. The context also posts `ModelContext.willSave` before it saves and `ModelContext.didSave` after a successful save, the latter carrying the inserted, updated and deleted identifiers; pass the context as the notification's `object` so you only hear your own. ## Inspecting pending work When a save surprises you, look at what the context is holding before it writes: - `insertedModelsArray`, `changedModelsArray` and `deletedModelsArray` list the pending inserts, edits and deletes. - A model's own `hasChanges` says whether that one object has unsaved edits, and `isDeleted` is `true` once it is marked for deletion, before the save removes it. - `container` tells you which container the context writes through, which matters when tests or extensions build several. ## rollback() and its limits `rollback()` **discards pending inserts and deletes, restores changed models to their most recent committed state, and empties the undo stack**. The key word is *committed*. On a context with autosave on, an edit may already have been saved, and then the "most recent committed state" **is** the edited state, so rollback leaves it in place. A Cancel button built on rollback therefore works reliably only when the edits have not been saved yet; Apple's own editing sample keeps a person's input in separate view state and copies it into the model only when they tap Save. ## A checklist for reviews - Background contexts: is there a `save()` at the end of the work, and inside long loops? - Critical writes on the main context: is there an explicit `save()` rather than reliance on autosave timing? - Error handling: is the thrown error from `save()` surfaced, not swallowed with `try?`? - Cancel paths: does the code expect `rollback()` to undo edits that autosave may have committed? - Wasted work: is `save()` guarded by `hasChanges` in code that runs often? The SwiftUI modifier's own autosave and undo switches are covered with SwiftData's SwiftUI integration.

  • A user edits an inspection in a sheet on the main context, then taps Cancel and the code calls rollback(). Why can the edit survive?
    `mainContext` autosaves, and `rollback()` only restores models to their most recent committed state. If autosave already saved the edit, that state includes it. Keep unconfirmed input outside the model, or edit in a context whose saves you control, and write to the model only on Save.
  • What does didSave give you that hasChanges does not?
    `hasChanges` is a yes or no about pending work in one context. The `ModelContext.didSave` notification fires after a successful save and its user info lists the inserted, updated and deleted identifiers, so other code can react to exactly what was written.

  • Every ModelContext autosaves by default, including ones you create yourself.
  • Autosave writes each change to disk the instant a property is set.
  • rollback() can always undo edits, even ones autosave already saved.
  • save() never fails, so try? is a fine way to call it.
  • Unsaved inserts in one context are visible to fetches in another context.