I am a little confused as to how to delete all core data in swift. I have created a button with an IBAction linked. On the click of the button I have the follow
Swift 5.1
Most of the posts here suggests to create a function to delete all entities by name and then delete all your entities by name. like so :
resetEntity(named: "MyEntity1")
resetEntity(named: "MyEntity2")
resetEntity(named: "MyEntity3")
...
But if the real question is how to clean ALL CoreData entity in one go, I suggest you loop over entity names:
// Supposing this is a CoreDataController/CoreDataStack class where you have access to `viewContext` and `persistantContainer`
// Otherwise just pass the `persistantContainer` as a parameter, from which you can also retrieve the `viewContext`
func resetAllCoreData() {
// get all entities and loop over them
let entityNames = self.persistentContainer.managedObjectModel.entities.map({ $0.name!})
entityNames.forEach { [weak self] entityName in
let deleteFetch = NSFetchRequest(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try self?.context.execute(deleteRequest)
try self?.context.save()
} catch {
// error
}
}
}
Hope this can help