iOS持久化Core Data之二 托管对象模型的迁移
2017-07-05 16:36
591 查看
说明:按照《Core Data 应用开发》的思路整理记录
如果对模型进行了结构化的更改,则需要把旧模型上数据迁移到新的模型上,否则映射错误,程序会崩溃。
在 CoreDataHelper 类中,loadStore 方法 中添加代码:
NSInferMappingModelAutomaticallyOption 为 YES 的话,Core Data 会以最合理的方式,把旧模型的实体属性对应到新模型的实体属性上。
有时我们会需要精确的控制,比如实体名和属性名发生变化,需要手工创建模型映射。
假设原实体为 Measurement 属性为 abc,现实体为 Amount 属性为 xyz,我们的工作是在新旧模型上,建立两者的映射。
创建 Mode2toModel3
旧:Source
新:Target
还要将 NSInferMappingModelAutomaticallyOption 设置为 NO
如果对模型进行了结构化的更改,则需要把旧模型上数据迁移到新的模型上,否则映射错误,程序会崩溃。
(一) 创建新的模型版本
(二) 轻量级的迁移方式
将新模型设为当前版本后,协调器会尝试用新的模型打开原有的存储区,在向协调器添加存储区的时候,我们需要传递 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 会以最合理的方式,把旧模型的实体属性对应到新模型的实体属性上。
4000
(三) 默认的迁移方式
有时我们会需要精确的控制,比如实体名和属性名发生变化,需要手工创建模型映射。假设原实体为 Measurement 属性为 abc,现实体为 Amount 属性为 xyz,我们的工作是在新旧模型上,建立两者的映射。
创建 Mode2toModel3
旧:Source
新:Target
还要将 NSInferMappingModelAutomaticallyOption 设置为 NO
相关文章推荐
- iOS持久化Core Data之三 托管对象模型的扩展
- iOS 数据持久化 CoreData的版本迁移
- Core Data中的模型与对象
- iOS Core Data: 存储自定义对象 Save Custom NSObject
- iOS CoreData数据迁移-默认迁移方式
- iOS 数据持久化 -- Core Data
- ios数据持久化--CoreData框架的介绍和使用
- IOS COREDATA SWIFT 创建关系和新建模型类
- iOS Core Data 数据迁移 指南
- iOS.数据持久化.PersistenceLayer.Core Data
- iOS CoreData数据迁移-迁移管理器迁移数据
- IOS APP 升级安装-coredata 的迁移,升级
- iOS 数据持久化之CoreData(二)堆栈建立和基本操作Demo
- iOS Core Data 数据迁移 指南
- iOS 6 编程--Core Data持久化数据存储(2)-使用Core Data实现简单ShoppingCart应用程序
- IOS数据持久化之Core Data(二) - 单表操作
- iOS CoreData详解(六)深入理解数据模型
- iOS开发 - CoreData框架 数据持久化
- iOS应用开发之Core Data数据持久化存储笔记
- Xcode8创建CoreData托管对象文件,编译报错