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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With