ObjC protocols from a Javascript standpoint

While browsing ObjC documentation or code, you'll sometimes see references to protocols, like NSKeyValueCoding. But what are they exactly ?

While writing Javascript, you need to mind the differences between each browser. Safari has a native getElementsByClassName, but it's not common yet. Before calling it, you verify that you can call it with if ('getElementsByClassName' in document) { document. getElementsByClassName(…) }. You expect document to implement getElementsByClassName, but you're not sure it does — so you test before calling. A protocol is just that : a list of methods that an object implements. Before calling them, you need to check their existence.

For example, an object conforming to the NSKeyValueCoding protocol means you can call [object valueForKey:@"myKey"]. If you're working with a vendor library and you're not sure its objects implement the protocol, do not call the method right away, check first its conformance with conformsToProtocol: or respondsToSelector:.

ObjC protocols exist because the language is dynamic : at any time, you can list all classes available in the runtime, query an object for the list of its methods, and call any method of any object — just like that ! Check out F-Script, a tool that injects itself into a running Cocoa app. You can open up a console, move windows around programmatically, change the contents of text fields … all of that dynamically.

In that respect, ObjC is much more closer to Javascript and Ruby than it is to C or C++. In vanilla C or C++, that kind of stuff just isn't available out of the box. For example in Half Life, Valve resorts to defining a static array for each class, describing each variable manually, in effect duplicating the definition of the class. This is tedious and much too prone to errors. In ObjC, it's automatic, always there, error-free.

In Ruby, protocols are called Duck Typing : If it walks like a duck, talks like a duck — it's a duck. It's the same thing : get an object, inspect its methods to check if it matches what you expect, and call the methods if they exist.

Objective-C from Javascript

Follow me on Twitter
Planet Cocoa

2011 02 22Distance field
2010 07 202Binding through NSApp
2010 05 122Forwarding invocations
2010 02 272Core Image black fringes
2010 02 21Quickest Way to Shell
2010 02 08Who's calling ?
2009 09 2138 ways to use Blocks in Snow Leopard
2009 08 182Bracket Mess
2009 08 124Taming JavascriptCore within and without WebView
2009 04 15Debugging with Activity Monitor
2009 03 25How Core Image Color Tracking works
2009 03 1510Custom NSThemeFrame
2009 03 10Which framework is running ?
2009 03 074CoreUI can paint pretty big
2009 02 18Localization with functions
2009 01 30Did you forget to nest alloc and init?
2009 01 16JSCocoa on the iPhone
2009 01 11Mixing WebView and JavascriptCore
2009 01 09Badge overflow
2009 01 09Find your Garbage Collection leaks with Instruments

Powered by MediaWiki