MacRuby and CoreData reading and writing

I am working on an iPhone project that uses CoreData. We need to pre-populate the database with a large dataset, for which the data is available on a number of CSV file.

I decided to use MacRuby 0.6 to build a tool to get the data out of the CVSs and into the CoreData's sqlite3 database. Although MacRuby (an implementation of Ruby 1.9 for Mac OS X) has really good APIs for CSV manipulation (a reason I decided to use MacRuby instead of Cocoa/Objective-C), the documentation on how to use CoreData with MacRuby was very thin, to say the least. But I did find some example code that got me started.

The full code is available on Github. But here's a couple of things I learned along the way.
  • Once you have a data model created on XCode, you need to compile it into a ".mom" file so that the Persistent Store Coordinator can be instantiated with it. This can be done with momc tool that comes with XCode available in /Developer/usr/bin (see gist example).
  • The relationship property names are used when you want to retrieve records, and the attribute property names for saving data.
  • In a one-many relationship, the object returned is an Array, through which you can iterate in Ruby with the "each" iterator.
  • In a one-one relationship, just use the entity name and its attribute property name.
This is the entity relationship diagram I used in the Github example:

Media_http1bpblogspot_rmhbr

About

Twitter