Post

Replies

Boosts

Views

Activity

SwiftUI TabView with List not refreshing after objected deleted from Core Data
Description:When an object in a list (created from a fetchrequest) is deleted from a context, and the context is saved, the list does not properly update.Error:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value (Thrown on line 5 below)struct DetailView: View { @ObservedObject var event: Event var body: some View { Text("\(event.timestamp!, formatter: dateFormatter)") .navigationBarTitle(Text("Detail")) } }Steps to reproduce:1. Create a new Master Detail App project with SwiftUI and Core Data.2. In the ContentView, set the body to a TabView with the first tab being the prebuilt NavigationView, and add a second arbitrary tab.struct ContentView: View { @Environment(\.managedObjectContext) var viewContext var body: some View { TabView { NavigationView { MasterView() .navigationBarTitle(Text("Master")) .navigationBarItems( leading: EditButton(), trailing: Button( action: { withAnimation { Event.create(in: self.viewContext) } } ) { Image(systemName: "plus") } ) Text("Detail view content goes here") .navigationBarTitle(Text("Detail")) } .navigationViewStyle(DoubleColumnNavigationViewStyle()) .tabItem { Text("Main") } Text("Other Tab") .tabItem { Text("Other Tab") } } } }3. Add a few items. Interact with those items in any way.4. Change tabs.5. Change back to Main Tab.6. Attempt to delete an item.Notes:The events: FetchResults<Event> appears to be updated properly following the deletion of the object. However, when the List is rerendered, an error occurs when trying to access the event's timestamp, because it wasn't removed from the list.The address of the managedObjectContext variable is the same in both the ContentView and the MasterView. This is known to be a problem when accesing the managedObjectContext from a modal view, as it must by passed again to ensure it is using the same context. This, however, does not seem to be an issue in this case.Details:XCode Version 11.3 (11C29)
4
0
5k
Dec ’19