Objective-C bridging fun

2008 May 17
by guenthernoack

Tacoma Narrows Bridge

Rick DeNatale’s article on the possibility of a Ruby fork mentions a very, very strange way to call Objective-C methods from Ruby.

A problem you’re faced with when bridging to Objective-C is its unusual method naming. When method name and parameters are usually written in a mixed fashion like [dict setObject: obj forKey: key] (with obj and key being parameters), programs using the bridge from the other language often end up being strange to read: (from the Etoile SVN repository, a bit shortened)

self picture drawAtPoint:fromRect:operation:fraction:(NSZeroPoint, rect,
    NSCompositeSourceOver, 1.0)

To overcome this problem, MacRuby introduces a very interesting mapping from messages to methods: (Quoted from the MacRuby homepage)

MacRuby enhanced the existing Ruby syntax to allow keyed arguments, as in Objective-C. As an example, you call dict.setObject(o, forKey:k). The new syntax can be used to send messages, but also to define new Objective-C methods.

In Ruby (from version 1.9 on), the forKey:k syntax is a keyword argument, equivalent to :forKey => k. Those keyword arguments are unordered, yet MacRuby tries to map them back to Objective-C methods, which can make using such calls non-deterministic (when you program to an interface, not an implementation).

Oh, wonderful world of dynamic languages!

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS