说明:按照《Core Data 应用开发》的思路整理记录
如果对模型进行了结构化的更改,则需要把旧模型上数据迁移到新的模型上,否则映射错误,程序会崩溃。
(一) 创建新的模型版本
(二) 轻量级的迁移方式
将新模型设为当前版本后,协调器会尝试用新的模型打开原有的存储区,在向协调器添加存储区的时候,我们需要传递 option 来指导协调器。
在 CoreDataHelper 类中,loadStore 方法 中添加代码:
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@"YES"
,NSInferMappingModelAutomaticallyOption:@"YES"
};
添加后 loadStore 方法如下:
//加载sqlite持久化文件
- (void)loadStore{
if(debug == 1){
NSLog(@"Running %@ '%@'", self.class,NSStringFromSelector(_cmd));
}
if(_store){return;}
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@"YES"
,NSInferMappingModelAutomaticallyOption:@"YES"
};
NSError *error = nil;
_store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:options error:&error];
if(!_store){
NSLog(@"Failed to add store. Error: %@", error);
}else{
if(debug == 1){
NSLog(@"Successfully added store: %@", _store);
}
}
}
其中 NSMigratePersistentStoresAutomaticallyOption 为 YES 的话,Core Data 会试着把低版本的持久化存储区迁移至新版本;
NSInferMappingModelAutomaticallyOption 为 YES 的话,Core Data 会以最合理的方式,把旧模型的实体属性对应到新模型的实体属性上。
(三) 默认的迁移方式
有时我们会需要精确的控制,比如实体名和属性名发生变化,需要手工创建模型映射。假设原实体为 Measurement 属性为 abc,现实体为 Amount 属性为 xyz,我们的工作是在新旧模型上,建立两者的映射。
创建 Mode2toModel3
旧:Source
新:Target
还要将 NSInferMappingModelAutomaticallyOption 设置为 NO