针对应用升级和表结构变动时 兼容旧版本的CoreData数据库解决办法
遇到的问题:
当你将CoreData 加入到工程中,并启动了App一切都运行良好,
可是开发途中修改了CoreData 的 数据结构,比如添加或者删除了某个字段,或者新添加了一张表.
此时,再运行App时,发现App直接Crash.
如何解决:
这说明CoreData无法做到时时的去修改表结构,但CoreData可以以多个副本的形式来处理数据结构变化时的Crash问题.
阐述一下原理: 原理类似SVN 需要打一个 tag 一样, 一担打了Tag 就意味着这个版本的代码将不再允许修改,如果需要修改,需要到新的分枝里去实现.
当利用开发工具新建CoreData 管理文件以后:xxx.xcdatamodeld 默认是只有一个分枝的.
那么添加分枝方式如下:
设置当前使用的coreData版本
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
<p style="margin-top: 0px; margin-bottom: 0px; font-size: 24px; font-family: Menlo; color: rgb(61, 29, 129);"><pre name="code" class="objc">if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])