Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData Migration of an Optional Relationship to a Non-Optional One

I am writing a Cocoa application that uses CoreData. 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. 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.

So my question is this: How do I create an NSManagedObject at migration-time to fill relationships that went from optional to non-optional?

like image 849
Nate Thorn Avatar asked May 18 '11 20:05

Nate Thorn


2 Answers

I believe the simplest way to go about this is by creating a separate script that reads from the old Core Data store and writes to the new one, creating any required objects on the fly as needed.

like image 120
Tarek Avatar answered Nov 01 '22 15:11

Tarek


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

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.

like image 33
Elise van Looij Avatar answered Nov 01 '22 13:11

Elise van Looij