Xcode 7 使用CoreData 关于数据库升级问题

来源:互联网 发布:淘宝助理一口价 编辑:程序博客网 时间:2024/05/17 09:26

coreData 很好用,但是也很坑

今天不说coreData 的具体使用,只提在实际运用中很关键的一种情况那就是数据库升级

以添加新字段为情形描述

先已有旧数据库,只有name age 两个字段

当你更新app版本时添加了一个新字段 address 这个时候如果直接将address 字段加入表内,运行就会崩溃

正确方法:

1.新建一个数据库分支  在Editor ->Add Model Version 新命名一个版本比如 coredatatest2

2.在工程的右边选择你新建的版本为当前版本



然后重新Editor ->Creat New NSMangeObject Subclass 这时新版本的数据模型就会将新字段关联上


3. 剩下一步是最关键的

修改- (NSPersistentStoreCoordinator *)persistentStoreCoordinator  方法内容

添加代码 

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

替换 条件

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options(这里以前是nil 现在替换为上面的options) error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }


这时候再运行代码可以观察数据库变化,新字段已经添加进去了






0 1
原创粉丝点击