Post

Replies

Boosts

Views

Activity

Reply to How to use a child context in SwiftData?
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. Extension on ModelContext: extension ModelContext { var child: ModelContext { let context = ModelContext(self.container) context.autosaveEnabled = false return context } } Presenting the sheet: .sheet(isPresented: $showAddSheet) { MySheet().environment(\.modelContext, context.child) } 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() }
Dec ’23