I have a SidebarView within a NavigationSplitView. The SidebarView is a list of users with a leading label.
When I try to swipe-delete an user from that list an error is thrown in my SideBarLabel View: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
It looks like that the label still exists after the user is deleted. How do I delete the complete row including label and user-object from CoreData?
I use this delete function but don't know how to manage to get rid of the users label:
my delete-func in SidebarView:
private func deleteSelectedUser(_ user: User){
print(user)
withAnimation {
moc.delete(user)
}
do {
try moc.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
my SidebarView code to create the list and swipe function:
import SwiftUI
import CoreData
struct SidebarView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: [SortDescriptor(\.name)])
var users: FetchedResults<User>
@Binding var selection: User.ID?
var body: some View {
List(selection: $selection) {
Text("Anwender")
.font(.headline)
.multilineTextAlignment(.leading)
ForEach(users) { user in
SidebarLabel(user: user)
.swipeActions { Button(role: .destructive, action: {
deleteSelectedUser(user)
//print("swiped item is: \(user.name!)")
}) {
Label("Remove User", systemImage: "trash")
} }
...
with that I create the label and the user in the list:
import SwiftUI
struct SidebarLabel: View {
//@Environment(\.managedObjectContext) var moc
@ObservedObject var user: User
var body: some View {
Label(user.name!, systemImage: "person.circle")
}
}

The reason you're hitting this is that your
deletecommand is happening asynchronously within thewithAnimationblock, which doesn't block the rest of that method. So by the time the code hitstry moc.save(), the object may not have actually been deleted. Then it's deleted from the context and not saved (until the next time you callsave()) – so it might still appear in the fetched results, but any attempt to access it will fail.Rather than putting the save in a
withAnimationblock, you could add an animation to the@FetchRequest, so that your delete method is cleaner:If you still find you're getting an error, you could be extra secure by checking whether the user has been deleted in your
SidebarLabel: