Using mogenerator — Code generation for Core Data — in Xcode 3.1

Data model

Core Data manages all the grubby details of data persistence and abstracts away the actual data layer (whether it's SQL and its object-relational impedance mismatch baggage or XML and the joy of serialization/de-serialization/rinse/repeat) for you. Actually, it does much more than that, such as handling undo/redo.

One area that I've been finding Core Data somewhat lacking is in the tools support in XCode for code generation. You can generate code using the Design → Data Model → Copy… Method Declarations/Implementations to Clipboard options but it's a convoluted and manual process. This is an all-the-more interesting oversight because the Core Data modeling tool in XCode is otherwise rather excellent.

mogenerator to the rescue!

To address this niche, Jonathan 'Wolf' Rentzsch has a free command-line tool called mogenerator. You can read Jon's motivations for building the tool, but don't follow the project links in that post as they're 404. You can also read about Jon's updates to the app in versions 1.2 and 1.5.

The latest release build, according to the project's SourceForge download page appears to be version 1.6.1 (157KB, .DMG).

An error with XCode 3.1.x

In the version of XCode that I'm running (don't you love how NDAs make you sound cryptic and mysterious? No, I didn't think so!), running mogenerator resulted in the following error:

sh: /Developer/Library/Xcode/Plug-ins/XDCoreDataModel.xdplugin/Contents/Resources/momc: No such file or directory
/Users/wolf/code/sf/redshed/cocoa/mogenerator/mogenerator.m:259: failed assertion `model'

It appears that since the last release build of mogenerator, the location of the momc app has changed. It's easy enough to fix this with a symbolic link so I didn't resort to compiling the latest from trunk which may or may not have the fix for this already implemented (see the new Trac and SVN repositories for the project for the latest updates).

If you'd rather use the release version like I did, the symbolic link you have to create is below (just run the command below in Terminal):

ln -s /Developer/usr/bin/momc /Developer/Library/Xcode/Plug-ins/XDCoreDataModel.xdplugin/Contents/Resources/momc

The simplest way to learn the app is to read the help via mogenerator --help and a simple example of its syntax is below:

mogenerator -m MyAwesomeApp.xcdatamodel -O Classes

That will generate four files for each Entity in your data model in the specified Classes folder. If, for example, you have an entity called User, it will create _User.h and _User.m, which hold the generated code (that you shouldn't edit yourself) and files for a _User subclass called User.h and User.m that you can use to implement your custom logic.

Comments