How to empty Core Data database of data?

What is the simplest way to completely empty contents of Core Data database and start like a new database with the same data model as emptied database?

Answered by KMT in 417258022

Yes, in code, of course. How do you get the db in the first place? You should have code that writes it out, empty, then either fills it with data, or it gets filled as the app is used. This is the easiest and most common approach.


Goes like this:

  1. App is installed
  2. App is first run
  3. DB is written out empty
  4. Any data that needs to be in place before use is written to the DB, skipped if not required
  5. User interacts with app/data


My suggestion is to start at #3, either by giving the user a 'reset DB' button, or hooking to whatever trigger is particular to your requirement.


As discussed in this years old SO thread, iterating thru each record to mass delete is at best a fragile approach, thus the recommendation to just wipe that store out and build a new empty one (give the user a 'reset' button): https://stackoverflow.com/questions/1077810/delete-reset-all-entries-in-core-data


Otherwise, if you're asking a database question on how to delete data, it would be better if you shed light on which type, etc. and if it's backed up via iCloud. But again, not recommended.


Makes me nervous, tho, that you're working with an otherwise complex data source and not familiar with the basics...not to mention this is not the CD forum. You've been here several years now and should have learned your way around a long time back. Or is this still a shared login?

I'd not bother with a clean out. Just repeat the original empty DB create/write with blank tables before adding data.

NSPersistentStoreCoordinator has a method call destroyPersistentStore...
How to empty Core Data database of data?
 
 
Q