SO, I have an application with several NSManagedObject
classes, and I'd like to extract some of the logic and put it into a self-contained framework, to be used in other applications.
I have a class like, let's say:
Employee
- firstName (an MOM property)
- lastName (an MOM property)
- (NSString *)fullName (a method)
- (NSUInteger)daysHired (an ObjC property)
- etc...
I'd love to provide this class, and it's MOM definition, in a framework. I figure this is possible by adding a .mom to the framework, defining Employee in there, building the class's .h and .m in the framework. When I want to reuse this class, I just have to include it into a project's build, merge the .mom in the framework with the .mom for the app, and the entities will be available. I guess?
However, I don't see how I can take an entity def/NSManagedObject subclass from the framework and then subclass or extend it in a new app. In order to make relations between my app's NSManagedObjects
and the abstract ones in the framework, I'd have to subclass the framework's entities -- I don't see how you can relate entites in one MOM file to entities in another MOM file, as either superclasses or as the destinations of relations.
Thoughts? Is it possible to provide an MOM in a framework?
It's true that it would be rather awkward to extend an entity in a compiled managed object model, for exactly the reason you describe. As I see it you have a few options, in descending order of convenience:
.xcdatamodel
instead of the compiled .mom
. Anyone who has the compiled model can easily reverse-engineer it anyway, so it's not like this gives away any extra information. With the raw model, sub-entities can be created as usual. If you're concerned about compatibility of the existing entities, add in run-time checks to look over Employee
and make sure it looks as you expect (for example, check the entity description's versionHash
). If the original framework model is updated, changes should merge cleanly-- provided that you use the Xcode 4 and higher file format for the model.NSEntityDescription
and then calling setEntities
on the managed object model. Just make sure you do so before loading a persistent store, because doing so after loading a store file will throw an exception.Employee
entity type a to-many relationship to it. Then you can add whatever key/value pairs you need at run time without needing to create a new sub-entity.Core Data wasn't really designed with this kind of use in mind but that doesn't mean it isn't possible. I'd go with the first option myself, but the others will work too.