runmad
runmad

Reputation: 14886

MagicalRecord: Remove entire data and setup core data stack again

For every app update, I would like to wipe my entire Core Data database completely and then set it up again. I have not been successful in doing so. I have tried various things, this seems to be the closest I have come. I found several SO posts, but none of the solutions have worked for my purposes.

I am using MagicalRecord, which provides several short hand methods for obtain various objects. Here's my code:

if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"buildVersion"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]) {
    NSPersistentStore *store = [NSPersistentStore defaultPersistentStore];
    NSError *error;
    NSURL *storeURL = [NSPersistentStore defaultLocalStoreUrl];
    NSPersistentStoreCoordinator *storeCoordinator = [NSPersistentStoreCoordinator defaultStoreCoordinator];
    [storeCoordinator removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    [[NSUserDefaults standardUserDefaults] setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"buildVersion"];
}

[MagicalRecord setupCoreDataStack];

Upvotes: 4

Views: 3517

Answers (1)

Sean Langley
Sean Langley

Reputation: 116

There is a NSPersistentStore+MagicalRecord category which allows you to get the URL for the persistent store:

+ (NSURL *) MR_urlForStoreName:(NSString *)storeFileName;

You can use the URL from this call to delete the persistent store SQLite db using NSFileManager.

Upvotes: 4

Related Questions