How to remove a core data persistent store

后端 未结 3 1024
终归单人心
终归单人心 2021-02-06 10:19

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)resetDatabas         


        
相关标签:
3条回答
  • 2021-02-06 10:47

    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;
    }
    
    0 讨论(0)
  • 2021-02-06 10:50

    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.

    0 讨论(0)
  • 2021-02-06 10:53

    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!

    0 讨论(0)
提交回复
热议问题