Delegates from a Javascript standpoint

In Javascript, you can change behaviour by setting your own code for events like onmousedown, onresize, onwindowclose. This is possible because functions in Javascript are first-class : they get treated as equally as numbers, strings, or any object. You can even replace a current object's method with your own, just with existingObject.someMethod = function () { … override behaviour here … }.

ObjC is a very light superset of C and thus functions get packed away the same as C in a huge blob of binary code, with just an adress to remember them by. But classes are first class in ObjC : you can query them anytime with [SomeClass someMethod], examine their methods, etc. Being written in ObjC, Cocoa will then let you change behaviour or get notifications by supplying a class, containing some specifically-named methods that it will call at the appropriate time : this is a delegate. (Recreating the same functionality in C would be tedious : you'd have to allocate a fixed-size structure containing pointers to functions, that delegate structure being specific to that object only, you'd have to set the ones you want to override to your global functions. In C++, you'd have to inherit from a base delegate class specific for that class expecting that delegate, override the functions you want … PWARK ! Being dynamic, ObjC is much more informal than that and will just check your class for specific methods names. )

Delegation is a way to extend behaviour without having to resort to derivation. Delegation is more flexible than derivation, but less flexible than Javascript's override.

But, as bonus side effects :

  • your code will be cleanly stored in an object with very descriptive method names
  • you can often use the same object as multiple delegates — In Webkit delegates, you can create one object that will be used as a notification recipient for page load, resource load, and resize.

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