向 coredata 添加新实体 - 我还能使用轻量级迁移吗?

gle*_*rey 3 cocoa-touch core-data ios

我有一个现有的核心数据集,我想向其中添加一个实体。我对在添加新实体将现有用户转换到新模型后是否可以使用轻量级迁移感到有些困惑。

当前模式是(仅显示实体):

Story 1toMany-> Sentences
Run Code Online (Sandbox Code Playgroud)

我需要:

Story 1toMany-> Sentences 1toMany-> Media
Run Code Online (Sandbox Code Playgroud)

我可以使用轻量级迁移工具来执行此操作吗?

我在文档中阅读过:

为了让 Core Data 能够生成推断映射模型,更改必须符合明显的迁移模式,例如:

简单添加新属性 移除属性 非可选属性变为可选 可选属性变为非可选,并定义默认值 重命名实体或属性

但是这个问题似乎表明轻量级迁移仍然可以与添加实体一起使用。由于新媒体实体是可选的,我看不出这实际上是一个问题。

小智 6

是的,您可能可以使用轻量级迁移。根据我的经验,我发现在对CoreData 模型进行更改之前,您需要在编辑器菜单下添加模型版本...。这样就可以映射前后场景。然后,您需要将新模型设置为当前模型。(您现在可以将实体添加到 Core Data 模型。确保您正在处理正确的模型。)

最后,您需要确保传递用于初始化 PersistentStoreCoordinator 的选项。

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool: YES],NSMigratePersistentStoresAutomaticallyOption,[NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption, nil];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {...
Run Code Online (Sandbox Code Playgroud)


J2t*_*heC 5

查看来自 wwdc 2010 的核心数据视频“掌握核心数据”。他们讨论了针对您的特定案例的迁移。长话短说:是的,您可以使用轻量级迁移。初始化 NSPersistentStoreCoordinator 实例时只需传递选项字典:

NSDictionary *dictionary=[NSDictionary dictionaryWithObjects:@[ [NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES]] forKeys:@[ NSMigratePersistentStoresAutomaticallyOption, NSInferMappingModelAutomaticallyOption]];
Run Code Online (Sandbox Code Playgroud)