Reset a CoreData persistent store Reset a CoreData persistent store multithreading multithreading

Reset a CoreData persistent store


For those attempting this on iOS9+, there are now the destroyPersistentStoreAtURL and replacePersistentStoreAtURL APIs.


If your goal is to empty the data store and reload it with new information, you may be better off using NSManagedObjectContext's reset and then loading in new data.

From NSManagedObjectContext's documentation

A context always has a “parent” persistent store coordinator which provides the model and dispatches requests to the various persistent stores containing the data. Without a coordinator, a context is not fully functional. The context’s coordinator provides the managed object model and handles persistency. All objects fetched from an external store are registered in a context together with a global identifier (an instance of NSManagedObjectID) that’s used to uniquely identify each object to the external store.

Removing the persistent store and using the managed object context associated with the store is probably the cause of the error.


Still not work! Abort caused by ManagedObjectContext link with invalid persistance store. Finally it work if I delete the ManagedObjectContext and let the app re-create later

Here is my modification

- (NSPersistentStoreCoordinator *)resetPersistentStore {  NSError *error = nil;  if ([persistentStoreCoordinator_ persistentStores] == nil)    return [self persistentStoreCoordinator];  [managedObjectContext_ release];  managedObjectContext_ = nil;  // FIXME: dirty. If there are many stores...  NSPersistentStore *store = [[persistentStoreCoordinator_ persistentStores] lastObject];  if (![persistentStoreCoordinator_ removePersistentStore:store error:&error]) {    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);    abort();  }    // Delete file  if ([[NSFileManager defaultManager] fileExistsAtPath:store.URL.path]) {    if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);      abort();    }   }  // Delete the reference to non-existing store  [persistentStoreCoordinator_ release];  persistentStoreCoordinator_ = nil;  NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];  return r;}