Search code examples
core-datanspersistentdocument

Exclude entity from NSPersistentDocument


I have an existing (and fully working) app using NSPersistentDocument to save the application files.
Now I need to create a new entity, this new entity is totally unrelated to the application files and it will contain the application cache, so I will use it to save on a separated file.
My project contains the MyDocument.xcdatamodeld used by NSPersistentDocument, to implement the new feature I created a new data model Cache.xcdatamodeld and added a new entity to the model (I have not written code just used XCode wizards) but when I run the app and try to open an existing app file I receive the error

The model used to open the store is incompatible with the one used to create the store

I understand this occurs because the model configuration for new entity is the same for NSPersistentDocument but how can I decouple it?
Creating a new configuration in data model doesn't work because the entity can't be deleted from the default one.
Any idea how to make NSPersistentDocument ignore the new entity and continue to work with the old data model?

I don't post source code because this happens simply adding the new model and entity to project


Solution

  • From the documentation of NSPersistDocument's managedObjectModel property:

    @property(readonly, strong) NSManagedObjectModel *managedObjectModel

    Discussion

    By default the Core Data framework creates a merged model from all models in the application bundle ([NSBundle mainBundle]). You can reimplement this property and return a specific model to use to create persistent stores. A typical implementation might include code similar to the following fragment:

    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *path = [bundle pathForResource:@"MyModel" ofType:@"mom"];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];