In my test app currently theres a button on top to add a group of six grocery entries. I'm trying to show the list of "entries" in the view and when tapped a detail .sheet modal is presented with the tapped/chosen item passed in. Then when the entry detail is tapped the item is deleted from storage.
I'm having two distinct issues:
the detail view only ever shows the first item in the entries. In this case, "Butter Detail" is always presented.
when tapped, the detail text crashes the app with the error "An NSManagedObjectContext cannot delete objects in other contexts". I though @StateObject could help me here but I'm still unclear on its implementation.
Code Block struct ContentView: View { @Environment(\.managedObjectContext) var managedObjectContext @FetchRequest(entity: Entry.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Entry.name, ascending: true)], predicate: nil) var entries: FetchedResults<Entry> @State var isPresented = false var body: some View { VStack { Button(action: { Entry.create(in: managedObjectContext) }) { Text("Button") } Text("\(entries.count)") List{ ForEach(entries, id: \.self) { entry in Text(entry.name ?? "Unknown") .onTapGesture { isPresented = true } .sheet(isPresented: $isPresented) { Detail(entry: entry) } } } } } } struct Detail: View { @Environment(\.managedObjectContext) var managedObjectContext @StateObject var entry: Entry var body: some View { Text("\(entry.name ?? "Error") Detail") .onTapGesture { do { managedObjectContext.delete(entry) try managedObjectContext.save() } catch { print(error) } } } }
after i posted my response, i did a quick edit after thinking about @State being used with a class -- but by the time i looked this up in my own code, it was too late to re-edit (posts close to editing after about ten minutes). sorry for the confusion.
i have two things for you:
i was right the first time in my code: @State should be used, not @ObservedObject.
be sure you have @State private var selectedEntry: Entry? SceneDelegate would only complain if you left off the private access control.
hope that helps,
DMG