天天看点

Core Data浅谈系列之九 : 使用Mapping Model

通常,我们都会尽量使数据模型的变化尽量简单。但有些情况下,不得不进行大的改动,甚至是重新设计数据模型。在这种情况下,之前提过的简单数据迁移已经无法适应了,需要引入mapping model这个中间层。

这时,又想起之前提过的一句话:

there is no problem in computer

science that can’t be solved by adding another level of indirection.

这里做一个简单的变动,先为球员增加薪水属性: 

Core Data浅谈系列之九 : 使用Mapping Model

然后创建一名球员,信息如下:

Core Data浅谈系列之九 : 使用Mapping Model

这时候我们打算为球员调薪,比如上涨10%。为了结合nsmappingmodel,这里简单地增加了一个新的属性newsalary,并且希望在数据迁移时更新该属性。为此,我们创建了一个nsmappingmodel映射模型:

Core Data浅谈系列之九 : 使用Mapping Model
Core Data浅谈系列之九 : 使用Mapping Model
Core Data浅谈系列之九 : 使用Mapping Model

选择好源数据模型和目标数据模型,设置newsalary和salary的关系:

Core Data浅谈系列之九 : 使用Mapping Model

这表示目标属性newsalary的值为源属性salary的1.1倍。

这个时候,我们不希望core data自动为我们映射模型,所以修改一下迁移选项: 

把nsinfermappingmodelautomaticallyoption设置为no后,我们需要手工指定映射模型:

接着,进行实质性的数据迁移。简单起见,这里就没有做错误检查了:

再跑一遍demo,然后在终端里查看:

Core Data浅谈系列之九 : 使用Mapping Model

可以发现有一份旧的sqlite文件和一份新的。

通过查看新的sqlite文件中的数据,可以得知newsalary的值: 

Core Data浅谈系列之九 : 使用Mapping Model

其中,newsalary为2420000.0,刚好是salary的值2200000.0的1.1倍。

brief talk about core data series, part 9 : using mapping model 

jason lee @ hangzhou

blog : http://blog.csdn.net/jasonblog

weibo : http://weibo.com/jasonmblog

继续阅读