5

I have made some changes to my Core Data model, and the we are handling the migration as described here: Lightweight Migration.

That's not a problem. However, I want to make a couple of other updates to my data that are conditional on the current model version. How can I get the name of the current model version? I expected to see something like:

[[NSBundle mainBundle] currentDataModelName]

but I can't seem to find it. Can anyone help?

Cesare
  • 9,139
  • 16
  • 78
  • 130
Ampers4nd
  • 787
  • 1
  • 11
  • 20

2 Answers2

7

You can get the model name and use it instead of model identifier. Check out this excellent article Custom Core Data Migrations and the corresponding Github code. With the help of the NSManagedObjectModel+MHWAdditions category you can retrieve the model name.


Source model name:

NSError *error;
NSString *storeType = ...;
NSURL *storeURL = ...;
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator  metadataForPersistentStoreOfType:storeType
                                                                                           URL:storeURL
                                                                                         error:&error];
NSManagedObjectModel *sourceModel = [NSManagedObjectModel mergedModelFromBundles:@[[NSBundle mainBundle]]
                                                                forStoreMetadata:sourceMetadata];
NSString *sourceModelName = [sourceModel mhw_modelName];


Destination model name:

NSString *destinationModelName = [[self managedObjectModel] mhw_modelName];

Assuming you implemented a managedModelObject getter. If not, here is out-of-the-box implementation.

- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }

    NSString *momPath = [[NSBundle mainBundle] pathForResource:@"YourModel" ofType:@"momd"];

    if (!momPath) {
        momPath = [[NSBundle mainBundle] pathForResource:@"YourModel" ofType:@"mom"];
    }

    NSURL *url = [NSURL fileURLWithPath:momPath];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
    return _managedObjectModel;
}


When migrating, the source model name and destination model name will differ. Otherwise, the names will be the same.

tonymontana
  • 5,728
  • 4
  • 34
  • 53
4

You can ask your NSManagedObjectModel by sending versionIdentifiers to the receiver.

- (NSSet *)versionIdentifiers

The docu is here

SAE
  • 1,609
  • 2
  • 18
  • 22
  • 2
    This works, but it's worth noting that version identifiers is empty by default, as noted here: http://stackoverflow.com/questions/3895156/nsmanagedobjectmodel-versionidentifiers, and in the documentation, so in order to determine if the model had changed, I had to manually set versionIdentifiers for the objectModel, then compare it to a value stored elsewhere (e.g. NSUserDefaults). – Ampers4nd Jan 22 '13 at 19:35