-1

I am very new to Swift and I would like to remove of the students I have in CoreData from Swift. I have coded this :

let fetchRequest: FetchRequest<Student> = FetchRequest(entity: Student.entity(), sortDescriptors: [])
var students: FetchedResults<Student> { fetchRequest.wrappedValue }
for student in students {
  do {
    try self.managedObjectContext.delete(student)
  } catch {
    print("error")
  }
}

but it crashes at run-time saying that I have an EXC_BAD_INSTRUCTION on the line where I initialize the students variable. What can I do to make this program correct?

Thanks for your help, Francois

InsideLoop
  • 6,063
  • 2
  • 28
  • 55
  • If I type `var students: FetchedResults = self.managedObjectContext.executeFetchRequest(fetchRequest)`, I get an error message `Cannot convert value of type '[Any]' to specified type 'FetchedResults'` and `Cannot convert value of type 'FetchRequest' to expected argument type 'NSFetchRequest'` – InsideLoop May 31 '20 at 11:07
  • Does this answer your question? [Core Data: Quickest way to delete all instances of an entity](https://stackoverflow.com/questions/1383598/core-data-quickest-way-to-delete-all-instances-of-an-entity) – Joakim Danielson May 31 '20 at 11:26

1 Answers1

1

To perform delete from CoreData on FetchedResults of an NSManagedObject, here's the code:

@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
    entity: Student.entity(),
    sortDescriptors: []
) var students: FetchedResults<Student>

func deleteAllStudents() {
    for student in students {
        managedObjectContext.delete(student)
    }
    do {
        try managedObjectContext.save()
    } catch {
        // handle the Core Data error
    }
}

If, you want to delete only a few entries then use this:

func removeStudents(at offsets: IndexSet) { // Could use [Student] instead too.
    for index in offsets {
        let student = students[index]
        managedObjectContext.delete(student)
    }
    // save context...
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47