Skip to content

Instantly share code, notes, and snippets.

@vascoorey
Last active August 29, 2015 13:59
Show Gist options
  • Save vascoorey/10992462 to your computer and use it in GitHub Desktop.
Save vascoorey/10992462 to your computer and use it in GitHub Desktop.
Delete CoreData store file in the event of a model mismatch
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
// Get the path for our model (in this case it's named 'cache')
NSURL *url = [[NSBundle mainBundle] URLForResource:@"cache" withExtension:@"momd"];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[[NSManagedObjectModel alloc] initWithContentsOfURL:url]]; /* get a coordinator */
NSString *sourceStoreType = nil;/* type for the source store, or nil if not known */ ;
NSString *path = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) firstObject];
// Figure out the full path where our store is located
path = [path stringByAppendingFormat:@"/%@/Cache", [[[[NSBundle mainBundle] bundleIdentifier] componentsSeparatedByString:@"."] lastObject]];
NSURL *sourceStoreURL = [NSURL fileURLWithPath:path]; /* URL for the source store */ ;
NSError *error = nil;
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:sourceStoreType
URL:sourceStoreURL
error:&error];
if (sourceMetadata == nil) {
NSLog(@"Error checking migration validity");
} else {
if (![[psc managedObjectModel] isConfiguration:nil compatibleWithStoreMetadata:sourceMetadata]) {
// A migration is needed.
// Delete CoreData store
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *directory = [[paths lastObject] stringByAppendingPathComponent:[[[[NSBundle mainBundle] bundleIdentifier] componentsSeparatedByString:@"."] lastObject]];
NSArray *files = [manager contentsOfDirectoryAtPath:directory error:nil];
NSError *error;
for(NSString *filename in files) {
[manager removeItemAtPath:[directory stringByAppendingPathComponent:filename] error:&error];
if(error) {
// handle error
}
}
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment