Skip to content

Delegate methods: There is NO magic. @cappuccino #cocoa

March 10, 2011

I have read many blogs and books about Cocoa and Cappuccino. Almost every one of them absolutely suck at explaining the Delegate design pattern used in Cocoa and Cappuccino. They say things like delegation describes “where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object.” That’s as useful as an umbrella in a hurricane.

Let me put it simply. A delegate method is … wait for it … a method.  That’s it. And what do you do with a delegate method. Frankly, anything you want your class to do when it receives that message. Again that’s it.

Certain Cocoa/Cappuccino classes have a property call delegate. They have statements that check to if delegate is not nil, and if it will respond to a certain message. If the answer to both of those is yes, it will send that particular message when it was programmed to send it.

For example, NSURLConnection/CPURLConnection is programmed to send the following message to its delegate:

[delegate  connection:self didReceiveData:data];

Don’t believe me look at the source code, you will find that statement in there.

And there is nothing magical about it.

On the flip side, if you created a class and included the method;

– (void)connection:(CPURLConnection)connection didReceiveData:(CPString)data

and you set an instance of your class as CPURLConnection’s delegate, then at the right time the CPURLConnection instance will send your class that message.

Pay attention, this is tricky now. What should I put inside a delegate method? The answer: ANYTHING YOU WANT. More specifically anything that you want to execute when your class receives that message. Maybe you want to do something with the data, maybe you want a spinner to disappear, maybe you want to draw a pretty flower on your screen…it doesn’t matter.

Questions?

Advertisements
One Comment
  1. I think the Gang of Four would have more to say about it—but screw the Gang of Four. This is an excellent description.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: