ios 如何为现有的核心数据实体添加更多属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16099055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:15:15  来源:igfitidea点击:

How to add more attributes to existing core data entity?

iphoneioscore-data

提问by Queshi Zakir

I have a project that is using core data , i need add more attributes(Columns) to existing entity (Column) , if i manually add attribute to data model app crash and it is due to context save which i used to insert data into table previously

我有一个使用核心数据的项目,我需要向现有实体(列)添加更多属性(列),如果我手动将属性添加到数据模型应用程序崩溃,这是由于我用来将数据插入表的上下文保存之前

Plz help .. Thank you

请帮忙..谢谢

采纳答案by chirag

If you want to change attributes in your existing code data model then you need to follow some steps... Please refer to this customizing-core-data-migrations

如果要更改现有代码数据模型中的属性,则需要执行一些步骤...请参阅此customizing-core-data-migrations

Or this would help you lot how-to-perform-a-lightweight-core-data-migration

或者这会帮助你很多how-to-perform-a-lightweight-core-data-migration

回答by Kevin Clifton

If you are only adding attributes to an entity, you can use the automated lightweight migrationin Core Data.

如果您只是向实体添加属性,则可以使用Core Data 中的自动轻量级迁移

Basically all you have to do is pass an NSDictionaryinstance with the appropriate options when you're adding the persistent store. Here's a code snippet from the end of an accessor method for _persistentStoreCoordinator:

基本上您所要做的就是NSDictionary在添加持久存储时通过适当的选项传递实例。这是访问器方法末尾的代码片段_persistentStoreCoordinator

NSNumber *optionYes = [NSNumber numberWithBool:YES];
NSDictionary *options = [NSDictionary dictionaryWithObjects:@[optionYes] forKeys:@[NSMigratePersistentStoresAutomaticallyOption]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    NSLog(@"Error opening persistent store: %@, %@", error, [error userInfo]);
    abort();
}
return _persistentStoreCoordinator;

If your migration is too complex for a lightweight migration, you'll see an error. Otherwise the migration should run and your database will be updated to match your new schema.

如果您的迁移对于轻量级迁移来说过于复杂,您会看到一个错误。否则迁移应该运行并且您的数据库将更新以匹配您的新模式。

Note that if you're doing this for real on a device, you should back up your .sqlite file first, in case something goes wrong in migration.

请注意,如果您在设备上真正执行此操作,则应首先备份 .sqlite 文件,以防迁移过程中出现问题。

回答by ipe

So my problem was I had no idea where this persistent store coordinator code goes. It turns out it is automatically created in your AppDelegateimplementation when you check "Use Core Data" when creating the project.

所以我的问题是我不知道这个持久存储协调器代码去哪里了。事实证明,AppDelegate当您在创建项目时选中“使用核心数据”时,它会在您的实现中自动创建。

So, from the second link here, all you need to do for a light-weight migration (adding new attributes and such) is the following:

因此,从这里的第二个链接开始,您需要为轻量级迁移(添加新属性等)执行以下操作:

  1. Select your .xcdatamodeld
  2. From the menu, choose Editor -> Add Model Version
  3. Name the new version anything you wish, select previous version in "Based on model"
  4. In File Inspector of the .xcdatamodeld, choose Model Version -> Current -> your new model version
  5. Select your new model version inside the .xcdatamodeld in Project Navigator, and do the changes to your model
  6. If you changed attribute names or types, create a mapping model, new file -> Core Data -> Mapping Model -> pick source and destination model versions
  7. Update the mapping in the new mapping model
  1. 选择您的 .xcdatamodeld
  2. 从菜单中选择编辑器 -> 添加模型版本
  3. 将新版本命名为您想要的任何名称,在“基于模型”中选择以前的版本
  4. 在 .xcdatamodeld 的 File Inspector 中,选择 Model Version -> Current -> your new model version
  5. 在 Project Navigator 中的 .xcdatamodeld 中选择您的新模型版本,并对您的模型进行更改
  6. 如果您更改了属性名称或类型,请创建映射模型,新文件 -> 核心数据 -> 映射模型 -> 选择源和目标模型版本
  7. 更新新映射模型中的映射

Change your AppDelegate persistent store coordinator code as follows.

如下更改您的 AppDelegate 持久存储协调器代码。

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
  var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
  let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("<data model name>.sqlite")
  var error: NSError? = nil
  var failureReason = "There was an error creating or loading the application's saved data."
  let options = [
    NSMigratePersistentStoresAutomaticallyOption: true,
    NSInferMappingModelAutomaticallyOption: true]
  if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, error: &error) == nil {
      coordinator = nil
      // Report any error we got.
      var dict = [String: AnyObject]()
      dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
      dict[NSLocalizedFailureReasonErrorKey] = failureReason
      dict[NSUnderlyingErrorKey] = error
      error = NSError(domain: "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()
  }

  return coordinator
}()

So you only add migration options to the addPersistentStoreWithTypecall.

因此,您只需向addPersistentStoreWithType呼叫添加迁移选项。