将实体添加到核心数据 [英] Adding Entity to Core Data

查看:138
本文介绍了将实体添加到核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用Core Data的应用程式。
在下一个版本中,我想向已经存在的实体添加一个新的实体。

We have an app that uses Core Data. In the next version I would like to add a new Entity to the already existing Entities.

只是添加新的实体,然后填充它

Is ok just to add the new one and then populate it from the software, or is there something that I have to think about?

推荐答案

有两种类型的迁移。最简单的是轻量级迁移和推断的映射模型 - 这意味着你只是告诉它做一个迁移,软件处理其余的。然而,警告是,它只能应付某些种类的变化。添加实体应该OK。

There's a couple of types of migration. The easiest is lightweight migration with an inferred mapping model — what that means is that you just tell it to do a migration and the software handles the rest. The caveat, however, is that it can only cope with certain kinds of changes. Adding an entity should be OK.

要启用轻量级迁移,您需要在打开持久存储时传递几个选项:

To enable lightweight migration, you need to pass in a few options when opening your persistent store:

NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

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

最后要做的就是更改数据模型,您需要添加模型版本。在Xcode 4中,在侧边栏中选择数据模型,从编辑器菜单中选择添加模型版本,然后命名新版本。然后您需要将新版本设置为活动版本:从左侧栏再次选择您的主数据模型文件,然后在右侧边栏,第一个选项卡,应该有一个版本化数据模型弹出菜单。

The one final thing to do is when making the change to your data model, you need to add a model version. In Xcode 4, select your data model in the sidebar, choose Add Model Version from the Editor menu, and name your new version. Then you need to set the new version as the active one: choose your main data model file from the left sidebar again, and then in the right sidebar, first tab, there should be a "Versioned Data Model" popup menu.

这是非常重要的。要进行迁移,Core Data需要使用旧存储创建的模型的版本以及要迁移到的版本。如果您没有旧版本,迁移将失败。

This is very important. To do a migration, Core Data needs the version of your model that the old store was created with, as well as the version you want to migrate to. If you don't have the old version, migration will fail.

这篇关于将实体添加到核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆