Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a core data persistent store

I need to delete my persistent store (doing it object by object is not practical because I have over 100,000 objects). I've tried this:

- (IBAction)resetDatabase:(id)sender {

    NSPersistentStore* store = [[__persistentStoreCoordinator persistentStores] lastObject];

    NSError *error = nil;
    NSURL *storeURL = store.URL;

    // release context and model
    [__managedObjectContext release];
    [__managedObjectModel release];
    __managedObjectModel = nil;
    __managedObjectContext = nil;

    [__persistentStoreCoordinator removePersistentStore:store error:nil];

    [__persistentStoreCoordinator release];
    __persistentStoreCoordinator = nil;

    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    if (error) {
        NSLog(@"filemanager error %@", error);
    }    

     // recreate the stack
     __managedObjectContext = [self managedObjectContext];

}

But I get this error when I try to insert entities into the store afterwards:

This NSPersistentStoreCoordinator has no persistent stores.  It cannot perform a save operation.

Update: I tried releasing the MOC and MOM before removing the persistent store but I still get the same error.

like image 536
David Avatar asked Apr 23 '11 01:04

David


1 Answers

Here is how I do a "reset data" function in several apps:

- (void)reset {
  // Release CoreData chain
  [_managedObjectContext release];
  _managedObjectContext = nil;
  [_managedObjectModel release];
  _managedObjectModel = nil;
  [_persistentStoreCoordinator release];
  _persistentStoreCoordinator = nil;

  // Delete the sqlite file
  NSError *error = nil;
  if ([fileManager fileExistsAtPath:_storeURL.path])
    [fileManager removeItemAtURL:_storeURL error:&error];
  // handle error...
}

Basically I just release the CoreData chain, then delete the persistentStore file. That's what you are trying to do, without using removePersistentStore, which I do not care since I will just rebuild the persistentStore coordinator later. Then at next core data call the chain is rebuilt transparently using singleton-lazy-style constructors like :

- (NSManagedObjectModel *) managedObjectModel {
  if (!_managedObjectModel)
    _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
  return _managedObjectModel;
}
like image 139
Vincent Guerci Avatar answered Oct 01 '22 22:10

Vincent Guerci