iOS App升级安装 - 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. 删除原来的类文件,重新生成下类。

在app delegate中

NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
                                   NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES],
                                   NSInferMappingModelAutomaticallyOption, nil];

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                              configuration:nil 
                                                        URL:storeUrl 
                                                    options:optionsDictionary 
                                                      error:&error]) {

      NSLog(@"failed to add persistent store with type to persistent store coordinator");

}

添加 *optionsDictionary,原来options:nil 改成options:optionsDictionary

重新编译下程序。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容