ios - 更改 CoreData 模型 : retro compatibility

标签 ios core-data model xcdatamodel

我一直在用 coredata 解决这个问题,这让我抓狂,因为它应该是直截了当的

我目前正在开发这个应用程序的第一个版本,很明显我一直在这里和那里调整核心数据模型,

然而,每次更改核心数据模型时,我都需要卸载应用程序并重新安装新版本。

这对我来说是可以接受的,但是一旦发布,我需要能够更改更新应用程序而无需我的用户重新安装。

我错过了什么,

我是否需要编写一些代码来告诉核心数据如何将现有持久数据修改为新数据?

谢谢你的帮助

杰森

最佳答案

核心数据模型 - 迁移 - 向当前数据模型添加新属性/字段 - 无需重置模拟器或应用程序

步骤:

  1. 从编辑器创建模型版本 - 给它任何有意义的名称,例如 ModelVersion2

  2. 转到该模型版本并对您的模型进行更改。

  3. 现在转到 YourProjectModel.xcdatamodeld 并将当前版本设置为新创建的版本。

  4. 将以下代码添加到您创建持久协调器的位置 -

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:

    [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,

    [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

并将选项值设置为方法的选项 -

[__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]

在我的例子中,它看起来像这样:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{

 if (__persistentStoreCoordinator != nil) {
    return__persistentStoreCoordinator;
 }

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


 NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LGDataModel.sqlite"];

  NSError *error = nil;
  __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  if (!   [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options  error:&error])
 {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }

  return__persistentStoreCoordinator;
 }

链接:https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmInitiating.html#//apple_ref/doc/uid/TP40004399-CH7-SW1

关于ios - 更改 CoreData 模型 : retro compatibility,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10374027/

相关文章:

ios - 如何拥有相同更新的对象的多个副本,同时在不同 View Controller 中实例化为单独的对象?

ios - 如何设置 PersistantStore 的自定义路径

ruby-on-rails - Rails 4. 模型中的国家/地区验证

c# - asp.net mvc 自定义模型绑定(bind)

ios - 使用 Storyboard instantiateviewcontrollerwithidentifier 在 tableView 之间传递数据

IOS 自定义键盘在横向模式下尺寸错误

unit-testing - 单元测试中的新核心数据堆栈 (PersistenceController)

java - 查找产品购买间隔

javascript - 如何在 React Native 中调用 AlertIOS

ios - 将 CKRecordID 保存到 CloudKit