Deleting all data in a Core Data entity in Swift 3

亡梦爱人 提交于 2019-12-02 17:28:01

You're thinking of NSBatchDeleteRequest, which was added in iOS 9. Create one like this:

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
let request = NSBatchDeleteRequest(fetchRequest: fetch)

You can also add a predicate if you only wanted to delete instances that match the predicate. To run the request:

let result = try managedObjectContext.executeRequest(request)

Note that batch requests don't update any of your current app state. If you have managed objects in memory that would be affected by the delete, you need to stop using them immediately.

Zonker.in.Geneva

To flesh out Tom's reply, this is what I added to have a complete routine:

func deleteAllRecords() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext

    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "CurrentCourse")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

    do {
        try context.execute(deleteRequest)
        try context.save()
    } catch {
        print ("There was an error")
    }
}

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<NSFetchRequestResult>(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")
            }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!