How to use a child context in SwiftData?

Hey there,

for my recent projects I used CoreData for persistence. One nice feature I use all the time is the ability to create a child context for editing operations.

When editing an entity in a form presented as a sheet, the changes made are only saved into the main context/parent context if the child context (I call this the editing context) is saved. Therefore dismissing an editing view results in destroying the child context and all the changes are discarded. Likewise when saving in the editing view, the changes will be proceeded to the parent context and persisted.

Is there any possibility to get the same or equivalent behavior when using SwiftData. Or is there another way to model this kind of cases?

All the best from Cologne, Germany!

An engineer answered this in the WWDC Slack. SwiftData does currently not support child contexts. A way around this would be to use a custom context, do the edits there and then apply them back to the mainContext and save it.

I use child contexts a lot in modal views with Core Data, so the apparent lack of child contexts in SwiftData has been bothering me. This may be a solution.

  1. Extension on ModelContext:
extension ModelContext {
    var child: ModelContext {
        let context = ModelContext(self.container)
        context.autosaveEnabled = false
        return context
    }
}
  1. Presenting the sheet:
.sheet(isPresented: $showAddSheet) {
    MySheet().environment(\.modelContext, context.child)
}
  1. Then the done button in the sheet inserts the @State model object and saves the context:
Button("Done") {
    do {
        context.insert(myModelObject)
        try context.save()
    } catch let error {
        ...
    }
    dismiss()
}
How to use a child context in SwiftData?
 
 
Q