CoreData数据库升级

如果IOS App 使用到CoreData,并且在上一个版本上有数据库更新(新增表、字段等操作),那在覆盖安装程序时就要进行CoreData数据库的迁移,具体操作如下:

1.选中你的mydata.xcdatamodeld文件,选择菜单editor->Add Model Version  比如取名:mydata2.xcdatamodel

2.设置当前版本 

   选择上级mydata.xcdatamodeld ,在inspector中的Versioned Core Data Model选择Current模版为mydata2

3.修改新数据模型mydata2,在新的文件上添加字段及表

4.删除原来的类文件,重新生成下类。

在appdelegate中

  1. NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],  
  2.                                        NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES],  
  3.                                        NSInferMappingModelAutomaticallyOption, nil];  
  4.       
  5. if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType   
  6.                                                   configuration:nil   
  7.                                                             URL:storeUrl   
  8.                                                         options:optionsDictionary   
  9.                                                           error:&error]) {  
  10.   
  11.           NSLog(@"failed to add persistent store with type to persistent store coordinator");  
  12.   
  13. }  
添加 *optionsDictionary,原来options:nil  改成options:optionsDictionary


5.重新编译下程序。

[原]iOS 升级程序中已有的CoreData

2013-12-4阅读586 评论0

也许在开发某个应用的1.0版本时,使用了CoreData。然后在2.0版本的时候,需要对CoreData做些修改。可能是增加一个实体(NSEnttity),可能是增加实体的属性(Property),或者创建删除实体间的关系(Relationship)等等。都需要对CoreData的结构做出修改。总结一下这部分知识。

创建一个使用CoreData的程序,勾上use arc选项。创建一个Sudent实体,其有两个属性,分别是name(NSString类型)和age(NSString类型)。效果如下图所示:

创建好之后,选中Studnet 实体,command + N,创建实体对应的对象。为了方便查看效果,创建如下图所示ui并关联了插入数据和打印数据的方法。

关联的方法如下图所示,简单的插入和打印CoreData里面的数据。

运行一下,先点“insert”,然后点“print”,看是否有数据打印。一切都可以运行,程序没有crash。好了,现在有个需求,是删除Student(实体)的age属性。下一步,决对不能对现有的model文件直接进行删除student的age操作。否则,再次运行coredata的时候,程序就会crash掉。

需要做的是:

 * 选中后缀是xcdatamodel的文件,Editor -> Add Model Vision - > finish 

      

发现model文件又多了一个,并且其中的一个还有对勾图案。又对勾图案的表明,目前使用该model文件。选中查看另外一个model文件,发现它和目前使用的model文件(又对勾标识的)是一样的。其实,他就是一份拷贝。现在,需要做的是在这份拷贝model文件中做修改,把(Student)实体的age属性删除.而原先的model文件不去做修改。

现在,我希望程序使用我修改之后的model文件。那么,选中CoreDataUpdate.xcdatemodeld文件,选中file inspector, 找到Model Version,将当前的model文件替换为CoreDataUpdate2

那么,现在绿色对勾标示的就是CoreDataUpdate2.xcdatemodel文件了。

重新生成(Student)实体所对应的类,以适应新的需求。

如果现在运行程序,程序依然会crash掉。还需要做一步修改。在创建的NSpersistentStoreCoordinator的地方,加上如下代码:

 NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption : @YES,

                              NSInferMappingModelAutomaticallyOption :@YES};

   if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:options error:&error])

这里,在创建NSPersistentStoreCoordinator的时候,会添加一个options的字典。

一切都会好起来的的。现在就可以运行了。

 

 
 
 
原文地址:https://www.cnblogs.com/fengmin/p/5015635.html