Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

iphone - Wipe all data stored with CoreData when the model has changed

I have an app that fetches data from the internet and uses CoreData to store them in the device, for a smoother experience.

Because I use Core Data, every time my schema changes, the app crashes when I try to run it with the previous data stored on the device. What is the fastest way to detect this change and wipe all the data from the device, since I don't mind redownloading them all. It beats crashing and remapping the schema to the new one (in my case).

I see that this check is performed in the getter:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

so I only need to know the methodology to implement for wiping the whole database and seting up Core Data again. Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...