Deleting all data in a Core Data entity in Swift 3

后端 未结 3 1794
孤独总比滥情好
孤独总比滥情好 2021-01-31 15:58

Is there a way to do a batch delete of all data stored in all of the entities in core data?

I read somewhere that in iOS 9 or 10 that apple introduced a way to do batch

3条回答
  •  伪装坚强ぢ
    2021-01-31 16:12

    Declare the Method for getting the Context in your CoreDataManager Class

         class func getContext() -> NSManagedObjectContext {
                guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
                    return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
                }
                if #available(iOS 10.0, *) {
                    return appDelegate.persistentContainer.viewContext
                } else {
                    return appDelegate.managedObjectContext
                }
            }
    

    Call the above method from your NSManagedObject subClass:

        class func deleteAllRecords() {
                //getting context from your Core Data Manager Class
                let managedContext = CoreDataManager.getContext()
                let deleteFetch = NSFetchRequest(entityName: "Your entity name")
                let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
                do {
                    try managedContext.execute(deleteRequest)
                    try managedContext.save()
                } catch {
                    print ("There is an error in deleting records")
                }
        }
    

提交回复
热议问题