Home > Software design >  Swift - Best way to delete all data from core data
Swift - Best way to delete all data from core data

Time:10-06

What is the best way to delete all data from core data? I found these two ways (I don't know if there's a better one)

I would like to know which one is the best (especially in terms of performance) and also a more up-to-date answer since most are already a few years old.

  1. Fetching all data e delete one by one
public func deleteAllData() {
    let ft = Entity.fetchRequest()
    if let dataFiltered = try? self.mainContext.fetch(ft) {
        dataFiltered.forEach { element in
            self.mainContext.delete(element)
        }
    }
}
  1. Using NSBatchDeleteRequest
public func deleteAllData() {
    let ft: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "EntityName")
    ft.includesPropertyValues = false
        
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: ft)
        
    try? self.container.persistentStoreCoordinator.execute(deleteRequest, with: self.mainContext)
}

-> Background code:

var mainContext: NSManagedObjectContext {
    return self.container.viewContext
}


var container: NSPersistentContainer = {
    let coreDataFileName = "CoreData"
    let container = NSPersistentContainer(name: coreDataFileName)
    container.loadPersistentStores() {_, error in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    }
    return container
}()

CodePudding user response:

I think Apple introduced "NSBatchDeleteRequest" from iOS 9. You should go for second one. It is the quickest one as far as I know.

  • Related