2008 03 23ObjC protocols from a Javascript standpoint
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
- KVC and KVO from a Javascript standpoint
- ObjC protocols from a Javascript standpoint
- Delegates from a Javascript standpoint
- Target+action from a Javascript standpoint
- Outlets from a Javascript standpoint
- Dynamic method over* from a Javascript standpoint
- The Responder Chain from a Javascript standpoint
- PerformSelector from a Javascript standpoint
- NIBs from a Javascript standpoint
- Events from a Javascript standpoint