Вытрите все данные, хранившие CoreData, когда модель изменится

Да они должны, только привести к беспорядку иначе.

9
задан Dimitris 22 November 2009 в 11:02
поделиться

1 ответ

Coming back to this question, to delete all the data from my CoreData storage I decided to simple delete the sqlite database file. So I just implemented the NSPersistentStoreCoordinator like this:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"myAppName.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {

        NSLog(@"Error opening the database. Deleting the file and trying again.");

        //delete the sqlite file and try again
        [[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:nil];
        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }

        //if the app did not quit, show the alert to inform the users that the data have been deleted
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error encountered while reading the database. Please allow all the data to download again." message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
        [alert show];
    }

    return persistentStoreCoordinator;
}
14
ответ дан 4 December 2019 в 14:28
поделиться