简体   繁体   English

CoreData将可选关系迁移到非可选关系

[英]CoreData Migration of an Optional Relationship to a Non-Optional One

I am writing a Cocoa application that uses CoreData. 我正在编写一个使用CoreData的Cocoa应用程序。 I have several versions out right now to the testers, and they want to be able to keep their data when they upgrade to the latest beta version. 我现在有几个版本给测试人员,他们希望能够在升级到最新测试版时保留他们的数据。 I've been using mapping models to migrate the database automatically so far from one version to another, no problem. 我一直在使用映射模型从一个版本到另一个版本自动迁移数据库,没问题。

But this time, I have to migrate a database where what was once an optional relationship becomes a non-optional relationship. 但是这一次,我必须迁移一个曾经是可选关系的数据库成为非可选关系。 When CoreData migrates to this version, it crashes, saying that the relationship is required. 当CoreData迁移到此版本时,它会崩溃,并说该关系是必需的。 This makes sense--how could it possibly know what to put in there for those objects without the relationship in the earlier version? 这是有道理的 - 如果在早期版本中没有关系的那些对象,它怎么可能知道放在哪里?

So I guess I need to write some code somewhere that creates a new managed object to fill the relationship if it's nil in the old database. 所以我想我需要在某处编写一些代码来创建一个新的托管对象来填充关系,如果它在旧数据库中为零。 I figure that might mean subclassing NSMigrationPolicy , but all the examples I find online show how to migrate attributes , but not relationships . 我想这可能意味着子类化NSMigrationPolicy ,但我在网上找到的所有示例都显示了如何迁移属性 ,而不是关系

So my question is this: How do I create an NSManagedObject at migration-time to fill relationships that went from optional to non-optional? 所以我的问题是: 如何在迁移时创建NSManagedObject来填充从可选到非可选的关系?

我认为最简单的方法是创建一个单独的脚本,从旧的Core Data存储读取并写入新的Core,根据需要动态创建任何所需的对象。

Interesting question. 有趣的问题。 I don't have a ready-made answer now, but I'd start with overriding - (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error 我现在没有现成的答案,但我首先要重写- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error

It seems like this would be the point where you could determine if a given instance (NSManagedObject *)sInstance has an empty relationship and if so, fill it. 看起来这可能是您可以确定给定实例(NSManagedObject *)sInstance是否具有空关系的点,如果是,请填写它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM