Core-data perform action after lightweight migration

176 views Asked by At

I have app which performs some lightweight migration when updating the core-data model.

However, I want to perform some specific actions after the migration has occurred as a one-off operation.

For example, I have two NSManagedObjects... Document and DocumentLayout. At the moment, there is no relationship between Document and DocumentLayout except by the app looking for a 'documentName' matching a 'layoutName' in the respective objects.

This is inefficient, so I want to create a true core-data relationship between the two and then after the migration has occurred, link the two objects by iterating through and creating the relationships.

I have looked at code such as ...

NSManagedObjectModel *destinationModel = [persistentStoreCoordinator managedObjectModel];
BOOL pscCompatibile = [destinationModel isConfiguration:nil compatibleWithStoreMetadata:sourceMetadata];

... to check if migration is required and do respective work but I need this to be a one-off operation as there may, during the lifetime of the app, be documents stored in Document which do not require a relationship with DocumentLayout and therefore if this operation runs each time an update is made to the data-model, a relationship will be created which is not what is required.

So, I could look at (say) a versionNumber flag in the app which detects this and only runs the operation once and prevents it running each time but this seems non-elegant and error-prone.

So, is there a way to run an operation once after a specific migration, then never run again?

1

There are 1 answers

1
Danny Bravo On

This is a really good question that I spent a lot of time trying to figure out. The best answer I have found so far can be found in this article from ObjC.io (I have no affiliation with them).

Apologies for just posting the link but I think the answer is a lot more complex than just a few lines of code.