1

After deleting all objects in Group, how to update UI ('reload' Query) ?

My function to delete all Group objects, in a Button action in toolbar :

    private func deleteAll() {
        print("delete all!")
        do {
            if try modelContext.delete(model: Group.self, where: NSPredicate(value: true), includeSubentities: false) {
                print("OK Groups cleared !")
            } else {
                print("Failed to clear Groups")
            }
        } catch {
            print("error: \(error)")
        }
    }

Updating attributes in a model triggers an UI/@Query update. But deleting all in code triggers nothing.

u0cram
  • 89
  • 6

1 Answers1

0

There isn't any useful documentation for the delete function you are using but I find it a bit strange that it has a parameter with the type NSPredicate instead of the newer Predicate. Anyway, in my test app for SwiftData I have a similar button in the tool bar that deletes all and using it the view (query) gets properly updated.

So maybe adjust and try the below code instead

Button("Delete all") {
    try? modelContext.fetch(FetchDescriptor<TestModel>()).forEach { modelContext.delete($0) }
    try? modelContext.save()
}

Hopefully we will get a working function that deletes all objects in one go soon.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52