Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of current core data model

Tags:

ios

core-data

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?

like image 408
Ampers4nd Avatar asked Dec 26 '22 11:12

Ampers4nd


2 Answers

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.

  • NSManagedObjectModel+MHWAdditions.h
  • NSManagedObjectModel+MHWAdditions.m


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.

like image 81
tonymontana Avatar answered Jan 05 '23 03:01

tonymontana


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

- (NSSet *)versionIdentifiers

The docu is here

like image 26
SAE Avatar answered Jan 05 '23 05:01

SAE