Deleting all data in a Core Data entity in Swift 3
Solution 1
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.
Solution 2
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")
}
}
Solution 3
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")
}
}
John Hubler
Jack-of-all-trades of web-design & development. I am well-versed in all aspects of web and mobile work including wireframing, designing, developing, and maintenance. I am currently working at Schoolwires, doing UX Design for our core products. I live and work out of Central Pennsylvania, and have been involved in web-design for nearly 16 years. My skillsets include: Coding: HTML5, CSS, PHP, MySQL, Javascript/jQuery, AJAX, JSON Software: The usual - Adobe, etc. Platforms: Wordpress, Joomla, Centricity2 Misc Skills: Responsive Web Design, Semantic Coding, Bulletproof Web-Design, Mobile Design Things I Like to Build: Custom Content Management Systems, Custom Web Apps, One-Page Websites Five Words That Describe My Style: Simple, Minimalistic, Clean, Bulletproof, Well-crafted
Updated on May 09, 2020Comments
-
John Hubler almost 4 years
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 deletes, but I can't seem to find any good information on it.
Ultimately, I just need a function that goes through an entity, and deletes all of the data in it. Seems like it should be simple enough, but documentation/tutorials for it have proven exceedingly difficult to find.
Any thoughts?
Edit
I added the following code into an IBAction attached to a button:
@IBAction func clearAllData(_ sender: AnyObject) { let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "PLProjects") let request = NSBatchDeleteRequest(fetchRequest: fetch) //get the data from core data getPLData() //reload the table view tableView.reloadData() }
This does not seem to work however. If I close down the project and reopen it, the data is still there. I am assuming this is also why the table view doesn't update, because the data is not actually being deleted.
-
John Hubler over 7 yearsI edited my post to show the code that I used - but that didn't seem to work for me. Basically I have a UITableView loaded into my view controller, and I am showing all of the "projects" in an entity called "PLProjects". I also have a button instance on the screen with an IBAction associated with it. The updates in my comment show the code in that IBAction - which fails to delete the items from the Core Data Entity, as well as failing to update the table.
-
Srivathsalachary Vangeepuram over 7 yearsIt's not enough to create the request. You have to execute it as well. Requests don't run automatically, they run when you tell them to run.
-
John Hubler over 7 yearsAh, sorry about that. I misunderstood what you had originally posted. I thought that the second snippet of code was to add a predicate. So - with that said - in the second snippet there, what is "moc"?
-
MrAn3 almost 7 yearsshouldn't you use the delegate variable for declaring the context?
-
guru about 5 yearsi have deleted records using above code but in next line when i fetch record, i am getting records. may be because of its asynchronous behaviour.do you have idea how to solve this problem?