November 30, 2009

MacRuby CoreData Tutorial

There is an useful tutorial on the Mac Developers Center about how to use CoreData programmatically. The tutorial has been ported to RubyCocoa here and partially on MacRuby as part of the template installed in XCode when you install MacRuby. With the help of both the sources I ported the tutorial to MacRuby introducing just a few ruby-isms but without altering the general structure of the program.

The tutorial is very useful if you intend to use CoreData to persist programmatically your objects without the visual help of Interface Builder. If you look at the listing below, you can see a “Run” object extending NSManagedObject persisted into the local store. The way CoreData works remembers me of EOF in WebObjects and it’s generally “old school” relational mapping and persistency. In this model, you request managed instances from the context and the context is then used to persist those objects. Persistency operations are not part of the object model like many ORM tools nowadays.

The following short example is just a starting point for a more abstract persistence API based on CoreData. Methods can be better encapsulated into smaller methods or different classes and in general I think it’d be a good idea to make it more ActiveRecord-like (i.e. transparent) for the final user to use. My intent here is to clone the original tutorial so please be patient if the code is not perfect and sorry for the odd line wrapping.

I tried this with MacRuby 0.5 beta 2. Just install MacRuby and run the example using the macruby command line interpreter. It will create a persistent XML store in ~/Library/Application Support/CoredataUtilityTutorial

Comments (View)
blog comments powered by Disqus