How to Sandbox SwiftData Edits in .sheet

Is this the right way to pass data to a sheet for editing?

struct Detail: View {
   
...

    // The single atomic source of truth for our sheet presentation
    @State var editorConfig: EditorConfig?
    
    // Completely encapsulated local configuration package
    struct EditorConfig: Identifiable {
        var id: PersistentIdentifier {
            item.persistentModelID
        }
        let context: ModelContext
        let item: Item
    }
    
    var body: some View {
       ...
                    Button("Edit") {
                        // 1. Spin up a separate scratchpad container layer
                        let context = ModelContext(modelContext.container)
                        context.autosaveEnabled = false
                        
                        // 2. Safely resolve our model inside the new isolated playground
                        if let sandboxItem = context.model(for: item.persistentModelID) as? Item {
                            // 3. Package it up to trigger the sheet presentation
                            editorConfig = EditorConfig(context: context, item: sandboxItem)
                        }
                    }
                }
            }
            // 4. SwiftUI tracks value replacement accurately without ghost state bugs
            .sheet(item: $editorConfig) { config in
                // Inject the isolated context into the sheet's environment chain
                EditorView(item: config.item)
                    .environment(\.modelContext, config.context)
            }
    }
}
Answered by Frameworks Engineer in 892390022

This shape looks great as long as some of the edge cases not shown in the snippets are handled correctly:

  1. handling failures of the as? Item
  2. calling context.save() at some point
  3. checking items are persisted (permanent IDs)
Accepted Answer

This shape looks great as long as some of the edge cases not shown in the snippets are handled correctly:

  1. handling failures of the as? Item
  2. calling context.save() at some point
  3. checking items are persisted (permanent IDs)
How to Sandbox SwiftData Edits in .sheet
 
 
Q