Last active
June 19, 2016 09:42
-
-
Save kean/7372e68f2568d33dc753376502134ae5 to your computer and use it in GitHub Desktop.
Tricking Core Data Into Performing Progressive Migrations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (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