2

I am new to coredata. Even so, I have managed to understand it within a certain degree and all is working fine. The only thing I was not able to do is to erase the whole database.

How do I do that?

I am on a ViewController and the database was initialized by the delegate. My project was based on Apple templates.

How do I erase the database and recreate it completely empty if it was created by the delegate?

Please refrain from pointing me to this "answer" Delete/Reset all entries in Core Data?

because it is not complete and do not covers how I recreate the whole thing. It just covers how to delete stuff.

thanks

Community
  • 1
  • 1
Duck
  • 34,902
  • 47
  • 248
  • 470
  • Just to be sure: you're asking how you can delete all objects and recreate them afterwards? Since you say "do not cover how I recreate the whole thing". – August Lilleaas Dec 13 '10 at 09:48

2 Answers2

2

I am not exactly sure why that answer isn't enough for you. But if you delete the store like this:` NSArray *stores = [persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];

    NSError *error = nil;
    [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:store.URL options:nil error:&error];
}

You can set the store back, just like I did in the last row:

[persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:store.URL options:nil error:&error];
Mikael
  • 3,572
  • 1
  • 30
  • 43
0

To delete the store, you can try something like this:

NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [docDirPath stringByAppendingPathComponent:@"YourDatabaseName.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:storePath]) {
[fileManager removeItemAtPath:storePath error:NULL];

And make sure you set the persistentStoreCoordinator to nil so when it is accessed again, it will reinitialise the database as if you were running the app for the first time.

self.persistentStoreCoordinator = nil;
Rog
  • 18,602
  • 6
  • 76
  • 97
  • thanks. I did that and the database is still there. The file is gone, but the data is there. I did a simple check on the data after that and I was able to list all values to terminal. Something is still holding it or was not refreshed. Zebulon's answer did the trick. Thanks anyway. – Duck Dec 13 '10 at 10:15