Skip to content

Instantly share code, notes, and snippets.

@kean
Last active June 19, 2016 09:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kean/7372e68f2568d33dc753376502134ae5 to your computer and use it in GitHub Desktop.
Save kean/7372e68f2568d33dc753376502134ae5 to your computer and use it in GitHub Desktop.
Tricking Core Data Into Performing Progressive Migrations
+ (BOOL)migrateStoreAtURL:(NSURL *)storeURL
models:(NSArray<NSManagedObjectModel *> *)moms // @[ mom_v1, mom_v2, mom_v3 ... ];
error:(NSError **)error {
// Find an index of the current store's mom
NSDictionary *meta = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:storeURL error:error];
if (!meta) {
return NO;
}
NSInteger idx = [moms indexOfObjectPassingTest:^BOOL(NSManagedObjectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
return [obj isConfiguration:nil compatibleWithStoreMetadata:meta];
}];
if (idx == NSNotFound) {
return NO;
}
// Progressively migrate between moms until final mom is reached
while (idx < (moms.count - 1)) {
@autoreleasepool {
NSManagedObjectModel *mom = moms[idx+1];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:@{ NSMigratePersistentStoresAutomaticallyOption : @YES,
NSInferMappingModelAutomaticallyOption : @YES }
error:error]) {
return NO;
}
idx += 1;
}
}
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment