Kataran
Kataran

Reputation: 165

CoreData crashes when saving filtered FetchedResults

I have a fetchRequest and then I filter the FetchedResults Array. If I display the filtered Objects in a list and try to delete one of them and save, it crashes.

I get this error code: Thread 1: Simultaneous accesses to 0x7fe28344eb28, but modification requires exclusive access

I tried to filter the fetchRequest with an NSPredicate, but then it crashed as well.

struct ListView: View {
    
    @FetchRequest(
        entity: Item.entity(), sortDescriptors: []
    ) var itemList: FetchedResults<Item>
    
    @Environment(\.managedObjectContext) var viewContext
    
    var filteredItemList: Array<Item> { 
        return itemList.filter { $0.name == "TestItem1" }
    }
    
    var body: some View {
        
        List {
            ForEach(filteredItemList, id: \.self) { item in
                Text(item.name)
            }
            .onDelete(perform: removeItem(at:))
        }
    }
    
    private func removeItem(at offsets: IndexSet) { // Zum Entfernen von Sets durch Wischfunktion
        
        for index in offsets {
            let item = filteredItemList[index]
            viewContext.delete(item)
        }
        
        try? self.viewContext.save()
    }
}

Upvotes: 2

Views: 164

Answers (1)

Kataran
Kataran

Reputation: 165

I found a way to delay some code in another stack overflow thread and now it works. I tested it with a delay of 0.1 seconds. Could even work with smaller delays.

Just add this code inside the removeItem Function.

let seconds = 0.1
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
             //Put your code which should be executed with a delay here
            try? self.viewContext.save()
            print("Saved")
        }

Upvotes: 1

Related Questions