How to remove a core data persistent store

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 04:22:16

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;
}

You can do it externally given that you only need to do this while developing your application. I have a terminal open in which I remove the store manually before re-running my app. All you need to know is where it is located. I log it to console everytime my app runs with the following code:

[[CoreDataSingleton sharedManager] managedObjectContext]; //be sure to create the store first!

//Find targeted mom file in the Resources directory
NSString *momPath = [[NSBundle mainBundle] pathForResource:@"Parking" ofType:@"mom"];
NSLog(@"momd path: %@",momPath);

Hope that helps!

You need to make sure that any managed object context attached to the persistent store have been released before you try to delete the store. Otherwise, the context will evoke that error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!