zoukankan      html  css  js  c++  java
  • iOS_SN_CoreData数据迁移

    最开始使用CoreData的时候碰到一个问题,就是当增加一个字段的时候再次运行APP会发生崩溃,一开始不知道什么原因,只知道是里面的表结构发生改变,就重新删掉APP再次安装是可以运行的,这样调试完后觉得不太靠谱,用户不可能删掉APP之后再次安装,上网查了一下是因为要进行数据迁移。

    Coredata提供了轻量级的自动数据迁移,比如以下三个情况会自动进行:

    1.简单的增加一个字段

    2.把一个必填字段改为可选字段

    3.把可选字段改为必填字段(但一定要定义默认值)

    数据迁移步骤:

    1、升级数据库模型:选中你的CoreDataTest.xcdatamodeld文件,选择菜单editor->Add Model Version 比如取名:CoreDataTest2.xcdatamodel

    2、设置当前版本:选择上级CoreDataTest.xcdatamodeld ,在inspector中的Versioned Core Data Model选择Current模版为CoreDataTest2(inspector界面,即为XCode工作区右侧工具栏)

    3、修改新数据模型CoreDataTest2,在新的文件上添加,修改或删除字段及表

    4、在程序启动时添加如下代码:

    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”);
    }
    

     5、重启一下XCode

    再次运行工程,完美

  • 相关阅读:
    73. Set Matrix Zeroes
    289. Game of Live
    212. Word Search II
    79. Word Search
    142. Linked List Cycle II
    141. Linked List Cycle
    287. Find the Duplicate Number
    260. Single Number III
    137. Single Number II
    Oracle EBS中有关Form的触发器的执行顺序
  • 原文地址:https://www.cnblogs.com/zhang-kiwi/p/5301138.html
Copyright © 2011-2022 走看看