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
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try coreDataManager.managedObjectContext.execute(batchDeleteRequest)
} catch {
print("Detele all data in \(entityName) error :", error)
}
To Delete all data you can use NSBatchDeleteRequest
func deleteAllData(entity: String)
{
let ReqVar = NSFetchRequest(entityName: entity)
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar)
do { try ContxtVar.executeRequest(DelAllReqVar) }
catch { print(error) }
}
This clean() method will fetch entities list from DataModel and clear all data.
func deleteAll(entityName: String) -> Error? {
if #available(iOS 9.0, *) {
do {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
try context.execute(batchDeleteRequest)
} catch {
return error
}
return nil
} else {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try context.fetch(fetchRequest)
for managedObject in results
{
if let managedObjectData:NSManagedObject = managedObject as? NSManagedObject {
context.delete(managedObjectData)
}
}
} catch {
return error
}
return nil
}
}
var objectModel: NSManagedObjectModel? {
if #available(iOS 10.0, *) {
return persistentContainer.managedObjectModel
} else {
return persistentStoreCoordinator?.managedObjectModel
}
}
open func clean() {
if let models = objectModel?.entities {
for entity in models {
if let entityName = entity.name {
_ = deleteAll(entityName: entityName)
}
}
}
}
Happy Coding!
You can use destroyPersistentStore
starting in iOS 9.0 and Swift 3:
public func clearDatabase() {
guard let url = persistentContainer.persistentStoreDescriptions.first?.url else { return }
let persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator
do {
try persistentStoreCoordinator.destroyPersistentStore(at:url!, ofType: NSSQLiteStoreType, options: nil)
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url!, options: nil)
} catch let error {
print("Attempted to clear persistent store: " + error.localizedDescription)
}
}
}
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<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try self?.context.execute(deleteRequest)
try self?.context.save()
} catch {
// error
}
}
}
Hope this can help
There are two simple methods as far as i know , first
Method 1:
// Initialize Fetch Request
let fetchRequest = NSFetchRequest(entityName: "Item")
// Configure Fetch Request
fetchRequest.includesPropertyValues = false
do {
let items = try managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
for item in items {
managedObjectContext.deleteObject(item)
}
// Save Changes
try managedObjectContext.save()
} catch {
// Error Handling
// ...
}
Methode 2:
// Create Fetch Request
let fetchRequest = NSFetchRequest(entityName: "Item")
// Create Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try managedObjectContext.executeRequest(batchDeleteRequest)
} catch {
// Error Handling
}
I have tested both and they both work fine