Talkin’ bout mogeneration

Building the Bipsync notes app

“Worth the effort for a consistent approach”

Once you’ve used Core Data for any length of time something becomes clear: keeping your concrete entity classes in sync with your model schema is a pain.

Xcode has a handy feature that allows for the generation of classes from the visual schema editor built in to the program, but it’s limited. Any generation process after the first won’t attempt to negotiate any customisations made to the class in the interim, meaning any additional methods, properties etc. are lost, and have to be added back in manually 1. This usually involves trawling through diffs to identify lost code, which aside from being error prone is also infeasible when significant schema changes are made.

Enter mogenerator, which is a command line tool that interprets your project’s xcdatamodel file and performs code generation in a similar, but smarter, way to Xcode. The principal difference is that mogenerator maintains two classes per entity, as opposed to Xcode’s one. The first class, prefixed with an underscore, is boilerplate similar to what Xcode would produce (the code is much less readable though, which is a shame. I know it’s not meant for editing but a little white space goes a long way in my opinion). The second class extends the first and is left to be customised as necessary by the developer. Crucially, the generation exercise can be repeated ad infinitum – only the boilerplate class will be updated as it is synchronised with the schema model file, ensuring all customisations and extensions remain intact.

This feature alone convinced us to start using the tool, despite an initial reluctance to introduce complexity into the development process. These fears have so far yet to be realised – once integrated into a project the tool is quite discreet, existing as it does as a separate build target that can be run on demand (we followed the advice in this article). It took a little time to port our existing classes (which made use of categories to mix in additional functionality to the boilerplate classes) but it was worth the effort for a consistent approach.

Check out mogenerator on Github.

1. Assuming subsequent generations can be performed – I’ve found this a little buggy, and often have to delete the files of existing classes before they can be generated again.