Deleting all data in a Core Data entity in Swift 3

后端 未结 3 1795
孤独总比滥情好
孤独总比滥情好 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<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")
                }
        }
    
    0 讨论(0)
  • 2021-01-31 16:13

    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")
        }
    }
    
    0 讨论(0)
  • 2021-01-31 16:15

    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.

    0 讨论(0)
提交回复
热议问题