In Core Data, how does a child context make an expense edit sheet cancellable, and what does saving that child context actually write?
answer
- a context whose parent is a context
- one store up
- throw the scratchpad away
- objectID into the child
basics
~20 sGive the sheet a context whose parent is viewContext and load the expense into it by objectID. Cancel just discards that child. Saving the child only pushes its changes into viewContext; nothing reaches the store until viewContext saves too.
solid answer
~30 sI create an `NSManagedObjectContext(.mainQueue)`, set its `parent` to `viewContext`, and load the tapped expense with `object(with:)` from its `objectID`. The sheet edits only that copy, so the list behind it keeps its values. On Cancel I discard the child or call `rollback()` on it; `viewContext` never saw the edits. On Save, `save()` on the child commits only one store up: the changes land in `viewContext`, which now `hasChanges`, and I must save `viewContext` for them to reach SQLite. The parent never pulls from its children, so a child that is never saved contributes nothing.
code
swift · 25 linesimport CoreData
@MainActor
final class ExpenseEditor {
let editContext: NSManagedObjectContext
let expense: NSManagedObject
init(expenseID: NSManagedObjectID, viewContext: NSManagedObjectContext) {
editContext = NSManagedObjectContext(.mainQueue)
editContext.parent = viewContext
expense = editContext.object(with: expenseID)
}
func saveTapped() throws {
guard editContext.hasChanges else { return }
try editContext.save() // pushes the edits into viewContext only
if let parent = editContext.parent, parent.hasChanges {
try parent.save() // this save reaches the store
}
}
func cancelTapped() {
editContext.rollback() // or just let the child context go
}
}go deeper
Remember that a child context's parent is another context, that edits made there stay invisible to the list until saved, and that throwing the child away cancels them.
Explain one-store-up saving: the child's save fills viewContext, viewContext's save fills the store, and the parent never pulls from children. Show loading the object with object(with:) from its objectID.
Cover the second save failing, temporary IDs for inserted objects, and a child going stale while an import edits the same row, with automaticallyMergesChangesFromParent and the merge policy as the levers.
Decide where child contexts are the house pattern for edits and where a direct viewContext edit is enough, and keep nesting shallow so every save chain stays easy to review.
## Contexts can have a context as parent Every managed object context has a **parent store**. Usually that is the `NSPersistentStoreCoordinator`, which talks to the SQLite file. Since iOS 5 it can instead be another context, set through the `parent` property. A context with a parent context is a **child context**; one whose `parent` is `nil` is a **root context**. Apple's documentation lists two uses for this: background work on another queue, and **discardable edits** such as an inspector or an edit sheet. The root of every chain must still be a coordinator. ## Building the edit sheet 1. Create the child: `let editContext = NSManagedObjectContext(.mainQueue)`. A sheet's controls run on the main thread, so a main-queue child fits; a private-queue child of `viewContext` is also allowed, because a parent can serve children on other queues. 2. Set `editContext.parent = viewContext`. 3. Load the row: `editContext.object(with: expense.objectID)`. This gives the sheet its own instance of the same expense, registered in the child. Editing the `viewContext` instance directly would change the object the list shows, and nothing could cleanly take that back. 4. Bind the sheet's fields to the child's object. Fetches and saves in the child are mediated by the parent context instead of the coordinator. ## What Save and Cancel do | Action | Child context | viewContext | Store | |---|---|---|---| | `editContext.save()` | clean again | receives the edits, `hasChanges` becomes true | unchanged | | then `viewContext.save()` | — | clean again | edits written | | Cancel: discard or `rollback()` | edits gone | untouched | untouched | The rule Apple states is that a save commits changes **only one store up**. "If you save a child context, changes are pushed to its parent," and they reach the persistent store only when the root context saves. The parent also **does not pull** changes from its children before it saves; a child you never save contributes nothing. For Cancel, the simplest code lets the child context go. `rollback()` is the explicit alternative: it removes everything from the undo stack, discards insertions and deletions, and restores updated objects to their last committed values, which for a child are the values it last loaded or saved. It does not refetch from the store. ## Details that bite - **Two saves, two failure points.** The child's save can succeed while `viewContext.save()` later fails validation or hits a merge conflict, so handle errors at the second save too. - **Temporary IDs.** An expense inserted in the child keeps a temporary `NSManagedObjectID` (`isTemporaryID` is true) until it is saved to a store. `obtainPermanentIDs(for:)` assigns a permanent one earlier when code needs a stable ID, but other contexts still cannot load the row until the root context saves it. - **Stale child.** The child holds the values it loaded. If an import changes the same expense while the sheet is open, the child does not update unless `automaticallyMergesChangesFromParent` is true on it, and then the merge policy decides what happens on save. - **Do not reuse a child as a cache.** A child context per sheet is cheap; a long-lived child gathers objects and drifts away from what `viewContext` shows. ## When not to use one A one-field toggle that saves at once does not need a child context; edit `viewContext` and save. The child pays off when a sheet holds several fields, inserts related objects or validates before committing, and the user must be able to walk away without a trace.
- Why not call rollback() on viewContext when the user cancels?The sheet's edits live only in the child, so `viewContext` has nothing of the sheet's to undo. Worse, `rollback()` on `viewContext` would discard any other unsaved changes there, from another screen or a pending action. Discard the child, or roll back the child, and leave the parent alone.
- How do you insert a brand-new expense from the sheet and show it in the list straight away?Insert it in the child, save the child so it appears in `viewContext`, then save `viewContext` so it gets a store row and a permanent ID. A fetched results controller or fetch on `viewContext` sees it after the child's save; other contexts see it only after the root save.
- Can a child context's own child exist, and where would its save go?Yes, contexts can nest more than one level. A grandchild's save goes into its parent, which must save into its parent, and so on until the root context's save reaches the store. Each level adds a save to remember, so most apps stop at one level.
A child context is a carbon copy clipped over the ledger page: scribble on it and tear it off on Cancel, and the ledger is untouched. Pressing it through copies the edits onto the page, but the ledger still has to be filed before anyone else sees them.
- Saying a child context's save() writes straight to the SQLite store.
- Editing the viewContext object in the sheet and hoping Cancel can take it back.
- Calling rollback() on viewContext to cancel edits made in a child context.
- Believing the parent pulls a child's unsaved changes when the parent saves.
- Passing the viewContext object itself into the child instead of loading it by objectID.