Skip to content

Instantly share code, notes, and snippets.

@ygit
Last active March 19, 2018 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygit/3e6f7f13a0eaa1aabf7efbae184e87b1 to your computer and use it in GitHub Desktop.
Save ygit/3e6f7f13a0eaa1aabf7efbae184e87b1 to your computer and use it in GitHub Desktop.
Core Data Persistent Store Migration
// for custom overwrites within an entity like changing an attribute from Boolean to NSNumber, etc
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
entityMapping:(NSEntityMapping *)mapping
manager:(NSMigrationManager *)manager
error:(NSError **)error {
NSManagedObject *newObject =
[NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName]
inManagedObjectContext:[manager destinationContext]];
// do transfer of nsdate to nsstring non-lightweight operations here
NSDate *date = [sInstance valueForKey:@"timeStamp"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
// set the value for our new object
[newObject setValue:[dateFormatter stringFromDate:date] forKey:@"printedDate"];
// do the coupling of old and new
[manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
return YES;
}
NSArray *mappingModelNames = @[@"Business", @"Tasks", @"Forms", @"ChatMessages"];
NSDictionary *options = @{
NSMigratePersistentStoresAutomaticallyOption : @YES,
NSInferMappingModelAutomaticallyOption : @YES
};
NSURL *destinationStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"HaptikLib.sqlite"];
for (NSString *mappingModelName in mappingModelNames) {
NSURL *modelURL = [HPBundle URLForResource:@"Haptik" withExtension:@"momd"];
NSMappingModel *mappingModel = [[NSMappingModel alloc] initWithContentsOfURL:fileURL];
NSMigrationManager *manager = [[NSMigrationManager alloc] initWithSourceModel:sourceModel
destinationModel:targetModel];
BOOL isSuccess = [migrationManager migrateStoreFromURL:sourceStoreURL
type:sourceStoreType
options:options
withMappingModel:mappingModel
toDestinationURL:destinationStoreURL
destinationType:destinationStoreType
destinationOptions:options
error:&error];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment