Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete/Reset all entries in Core Data?

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.

like image 409
Michael Grinich Avatar asked Jul 03 '09 04:07

Michael Grinich


People also ask

How do I delete all entries in Core Data?

One approach to delete everything and reset Core Data is to destroy the persistent store. Deleting and re-creating the persistent store will delete all objects in Core Data.

What is delete rule in Core Data?

A delete rule defines what happens when the record that owns the relationship is deleted. Select the notes relationship of the Category entity and open the Data Model Inspector on the right. By default, the delete rule of a relationship is set to nullify. Core Data supports four delete rules: No Action.

How do I delete Core Data in Swift 4?

Table views have a built-in swipe to delete mechanic that we can draw upon to let users delete commits in our app. Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or location in the object graph.


1 Answers

You can still delete the file programmatically, using the NSFileManager:removeItemAtPath:: method.

NSPersistentStore *store = ...; NSError *error; NSURL *storeURL = store.URL; NSPersistentStoreCoordinator *storeCoordinator = ...; [storeCoordinator removePersistentStore:store error:&error]; [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error]; 

Then, just add the persistent store back to ensure it is recreated properly.

The programmatic way for iterating through each entity is both slower and prone to error. The use for doing it that way is if you want to delete some entities and not others. However you still need to make sure you retain referential integrity or you won't be able to persist your changes.

Just removing the store and recreating it is both fast and safe, and can certainly be done programatically at runtime.

Update for iOS5+

With the introduction of external binary storage (allowsExternalBinaryDataStorage or Store in External Record File) in iOS 5 and OS X 10.7, simply deleting files pointed by storeURLs is not enough. You'll leave the external record files behind. Since the naming scheme of these external record files is not public, I don't have a universal solution yet. – an0 May 8 '12 at 23:00

like image 199
groundhog Avatar answered Sep 18 '22 13:09

groundhog