Coredata provides a lightweight auto data migration method for the following conditions:
1. Simply add a new column.
2. Change a column to optional.
3. Change a optional column to compulsory, but have default value.
Step 1:
Create a new data version
1. Editor -> Add Model Version (expand your xcdatamodeld item) , type a name
2. Client on the xxxx.xcdatamodeld file and in the attribute page, set the current version
Step 2:
1. In App delegate , in method "persistentStoreCoordinator" change as follow:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"WorkXP.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// handle db upgrade
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
// Handle error
}
return __persistentStoreCoordinator;
}
After that, for a lightweight data migration, user don't need to remove the old version app before they install the new one.
No comments:
Post a Comment