Can't merge models in managedObjectContext (basic Coredata)
I'm running into an error that seems to involve migrations, but I'm not using any migrations. Still basic Core Data stuff here.
I have an existing application to which I'm trying to add Core Data. I've put the relevant code in my App Delegate. The application is a basic tab application.
How do I access Core Data in other controllers besides the delegate? After Googling, I thought the way was to do something like this:
开发者_JAVA技巧app = (RootAppDelegate*)[UIApplication sharedApplication].delegate;
FirstViewController.managedObjectContext = app.managedObjectContext;
When I do this I get:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't merge models with two different entities named 'Event'
What am I doing wrong here?
You've probably got two or more .xdatamodel files in the project, each with an Entity
attribute. That is the entity that gets generated by the Xcode template projects so you've probably duplicated one of the template data model files.
You are getting the error in your controllers because the template app delegate does not initialize the Core Data stack until it's managedObjectContext attribute is accessed. Accessing the managedObjectContext attribute triggers the loading of the managedObjectModel attribute. The templates create the model using mergedModelFromBundles:
which sweeps up all the model files in the app bundle and attempts to build a single model from them.
If you have two or more models with an entity of the same name, you get the error you see. The merge
in this context has nothing to do with migration but rather the merging of multiple model files used in the same version.
Did you change your model (during the dev process) and the application is installed on device/sim with the previous model?
If so just remove the app and re-run and it should work fine.
How do I access Core Data in other controllers besides the delegate?
The preferred way to access a NSManagedObjectContext is through a NSManagedObject instance. For example:
[anEntity managedObjectContext];
You can also pass a reference of the NSManagedObjectContext to the view controllers that require it.
Update:
If you have enabled automatic migrations when you setup your persistent store coordinator, this post suggests that you would need to perform some additional steps in your managedObjectModel accessor:
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *path = [[NSBundle mainBundle] pathForResource:@"Event" ofType:@"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
return managedObjectModel;
}
This is an older solution (not sure it will still do the trick).
精彩评论