skip to content

A SwiftData journal app's entry editor binds a Form to the model with @Bindable, yet tapping Cancel keeps the edits; why, and how do you fix it?

level: seniorimportance: should knowfreq 45%

answer

  1. the binding writes into the live model
  2. @Model adds Observable conformance
  3. autosave on the main context
  4. rollback restores only to the last save
  5. draft in @State, write on Save

basics

~20 s

@Bindable bindings write every keystroke straight into the managed model, and the main context autosaves, so dismissing changes nothing. Edit a draft in @State and copy it to the model on Save, or edit in a separate context without autosave.

solid answer

~50 s

`@Model` makes the class `Observable`, so `@Bindable var entry: Entry` hands the `Form` bindings like `$entry.title` that write directly into the object the main context tracks, on every keystroke. The environment context has autosave on by default, and Apple documents that it saves after changes to registered models and at lifecycle points of windows, views and sheets. `dismiss()` only closes the sheet. Calling `rollback()` on Cancel is not reliable either: it restores the last saved state, which autosave may already have moved forward. The fix Apple's own editing sample uses: copy the fields into `@State` on appear, bind the form to those, and assign them to the model only in Save; for a new entry, create and insert the model in Save too. A heavier alternative is a separate `ModelContext` on the same container, injected with `modelContext(_:)`, where autosave is off by default.

code

swift · 20 lines
swift
import SwiftUI
import SwiftData

// Bug: every keystroke writes into the model the main context autosaves.
struct LiveEntryEditor: View {
    @Bindable var entry: Entry
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        Form {
            TextField("Title", text: $entry.title)
            TextField("Entry", text: $entry.text, axis: .vertical)
        }
        .toolbar {
            ToolbarItem(placement: .cancellationAction) {
                Button("Cancel") { dismiss() }
            }
        }
    }
}

go deeper

for a junior

Recall that @Bindable on a SwiftData model edits the real stored object, not a copy.

for a middle

Explain the chain: @Model is Observable, the binding writes the tracked model, the main context autosaves, dismiss() restores nothing.

for a senior

Diagnose why rollback() is unreliable under autosave and pick draft state or a scratch context, with inserts moved into Save.

for a principal

Set a team rule that any editor with Cancel binds to a draft, and that live @Bindable editing is reserved for screens without one.

## The symptom A journaling app presents an editor sheet for an entry. The form fields are bound to the model itself: ```swift @Bindable var entry: Entry // ... TextField("Title", text: $entry.title) ``` The person changes the title, taps **Cancel**, and the list behind the sheet already shows the new title. After a relaunch the edit is still there. ## Why it happens Three facts combine: 1. **The binding targets the live model.** `@Model` adds `Observable` conformance to the class, so SwiftUI's `@Bindable` can project bindings to its properties. Those bindings read and write the **same object** the context tracks. There is no copy; each keystroke assigns `entry.title`. 2. **The context tracks every change.** The entry came from the main context (through `@Query` or a fetch), so the context records the assignment as a pending change at once. Other views that read `entry.title`, such as the list row, redraw immediately because the model is observable. 3. **The main context autosaves.** The `modelContainer` modifier enables autosave by default. Apple's `autosaveEnabled` documentation says such a context calls `save()` after changes to inserted or registered models, and also at various times during the lifecycle of windows, scenes, views and sheets. `dismiss()` closes the sheet and nothing more. Nothing in the chain ever kept the old value. ## Why rollback() is not the fix `ModelContext.rollback()` discards pending inserts and deletes and restores changed models to their **most recent saved state**. With autosave on, the most recent save may already include the edit, so a rollback on Cancel restores the edited title. It can appear to work in a quick test and fail when autosave happened to run first. ## Fixes | Approach | How it works | Cost | |---|---|---| | Draft in `@State` | Copy fields into `@State` on appear, bind the form to them, assign to the model in Save | A few extra properties; the approach in Apple's editing sample | | Scratch context | Create `ModelContext(container)` (autosave is `false` by default for contexts you create), load the entry there, inject it with `modelContext(_:)`, call `save()` on Save | More moving parts; the main context must pick up the saved change | | Turn off autosave globally | Stop the main context saving on its own | Wrong: the edit still sits in the main context, and the next `save()` anywhere writes it | Apple's sample "Adding and editing persistent data in your app" takes the first route and states the reason: state variables separate what a person types from the data in the model, so SwiftData does not save changes until the person is ready, and they can discard them. For a **new** entry the same rule applies: do not insert an empty `Entry` before showing the editor, because autosave can keep a blank entry when the person cancels. Create the model and call `modelContext.insert(_:)` inside the Save action, as Apple's sample does. ## Where @Bindable is still right Live editing is a valid design for screens without Cancel, such as an inline notes field that should persist as you type. The rule is about matching the binding to the product decision: - **no Cancel button**: `@Bindable` on the model is the simplest correct code; - **Cancel must discard**: bind to a draft, or to a model in a context that will not save on its own; - **undo instead of Cancel**: `isUndoEnabled: true` lets people undo changes saved to the main context with system gestures, which is a different interaction from a Cancel button. ## Warning before discarding With a draft or a scratch context, Cancel can also tell whether there is anything to lose. In the draft approach, compare the `@State` values with the model's. In the scratch-context approach, `ModelContext.hasChanges` reports whether that context holds unsaved changes, which is a clean trigger for a "Discard changes?" confirmation. Neither check works in the original bug, because the main context may already have saved the edits and has nothing pending. ## Checklist for review - Does the editor have a Cancel or Discard action? Then bindings must not target a model in an autosaving context. - Is a new model inserted before the person commits? Move the insert into Save. - Does anyone rely on `rollback()` to undo edits in the main context? Check whether autosave can run first.

  • Would disabling autosave on the main context fix Cancel?
    No. The edit still lives in the main context as a pending change, visible to every view that reads the entry, and the next `save()` from any code path writes it. Autosave only decides when saving happens; the problem is that the form wrote into the tracked model at all.
  • How does the scratch-context variant work?
    Create `ModelContext(container)`, whose `autosaveEnabled` defaults to `false`, load the entry into it, and present the editor with `.modelContext(scratch)` so it binds to that copy with `@Bindable`. Save calls `try scratch.save()`; Cancel simply drops the context, and its unsaved changes go with it.

  • @Bindable gives the form a copy, so edits stay local until saved.
  • Dismissing a sheet discards the changes it made to a model.
  • Calling rollback() on Cancel always restores the entry, even with autosave on.
  • Turning off autosave for the whole container is the right fix.
  • Insert the blank new entry first, then let Cancel clean it up.