MacRuby

MacRuby as a CoreData playground

December 4th, 2009  |  Published in MacRuby, Ruby, iPhonedev

Lately I’ve been working to optimize a Core Data based iPhone app. Core Data has generally been a pleasure to work (along with great developer support from Apple), but as soon as I’ve needed to dig in to work with more complex (read: slow) queries, a few cracks appeared. For example, improper predicates don’t crash or return errors: they just never return. Factor in compile / run / get the app to the right spot, and the debug cycles are painful.

So eyeing (and looking for a productive reason to play/learn…) the latest MacRuby build I thought it might be useful to see if I couldn’t iterate with Ruby when testing more complex predicates to eliminate the entire compile/run phase. After a bit of fiddling, I was able to get this to work quite nicely.

Here is some basic Ruby for use with macirb to illustrate this technique…

framework 'cocoa'
 
modelURL = NSURL.fileURLWithPath('MyCoreData.mom')
storeURL = NSURL.fileURLWithPath('MyCoreData.sqlite')
mom = NSManagedObjectModel.alloc.initWithContentsOfURL(modelURL)
psc = NSPersistentStoreCoordinator.alloc.initWithManagedObjectModel(mom)
ps = psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: nil)
moc = NSManagedObjectContext.alloc.init
moc.setPersistentStoreCoordinator(psc)
 
fetch = NSFetchRequest.alloc.init
fetch.setEntity(NSEntityDescription.entityForName('Employee', inManagedObjectContext: moc))
fetch.setFetchLimit(25)
results = moc.executeFetchRequest(fetch, error: nil)