Get the name of the current kernel data model

I made some changes to my Core Data model, and we handle the migration as described here: Easy migration .

It's not a problem. However, I want to make several other updates to my data, which are due to the current version of the model. How can I get the name of the current version of the model? I expected to see something like:

 [[NSBundle mainBundle] currentDataModelName] 

but I can not find it. Can anyone help?

+4
source share
2 answers

You can set your NSManagedObjectModel by sending versionIdentifiers receiver.

 - (NSSet *)versionIdentifiers 

Document here

+3
source

You can get the model name and use it instead of the model identifier. Check out this great Custom Core Data Migrations article and related Github code . Using the NSManagedObjectModel + MHWAdditions category, you can get the model name.


Source Model :

 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]; 


Target Model :

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

Assuming you have implemented getter managedModelObject . If not, then this is a finished 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 name of the source model and the name of the target model will be different. Otherwise, the names will be the same.

+4
source

All Articles