Leave a comment

Delete/Reset all entries in CoreData

Here is one useful method of how we can delete all entries of our database:

NSPersistentStore *store = [self.persistentStoreCoordinator.persistentStores lastObject];

NSError *error = nil;

NSURL *storeURL = store.URL;

[self.persistentStoreCoordinator removePersistentStore:store error:&error];

[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

{

// do something with the 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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: