Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.
Edit
I'm looking to do this programmatically so that a user can essentially hit a reset
button.
Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.
Edit
I'm looking to do this programmatically so that a user can essentially hit a reset
button.
here my swift3 version for delete all records. 'Users' is entity name
you're all making this seem complicated. You can just send your NSManagedObjectContext the reset method
Here's a version that deletes every record in every table you have.
Swift 4
Updated Solution for iOS 9+
Use
NSBatchDeleteRequest
to delete all the objects in the entity without having to load them into memory or iterate through them.This code has been updated for iOS 10 and Swift 3. If you need to support iOS 9, see this question.
Sources:
[Late answer in response to a bounty asking for newer responses]
Looking over earlier answers,
But there's a different, similar approach to removing the persistent store that does work. The key is to put your persistent store file in its own sub-directory that doesn't contain anything else. Don't just stick it in the documents directory (or wherever), create a new sub-directory just for the persistent store. The contents of that directory will end up being the persistent store file, the journal files, and the external binary files. If you want to nuke the entire data store, delete that directory and they'll all disappear.
You'd do something like this when setting up your persistent store:
Then when you wanted to remove the store,
That recursively removes both the custom sub-directory and all of the Core Data files in it.
This only works if you don't already have your persistent store in the same folder as other, important data. Like the documents directory, which probably has other useful stuff in it. If that's your situation, you could get the same effect by looking for files that you do want to keep and removing everything else. Something like:
This approach may be error prone. You've got to be absolutely sure that you know every file you want to keep, because otherwise you might remove important data. On the other hand, you can remove the external binary files without actually knowing the file/directory name used to store them.