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?
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.
You can ask your NSManagedObjectModel
by sending versionIdentifiers
to the receiver.
- (NSSet *)versionIdentifiers
The docu is here
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