views:

70

answers:

4

Hello, I am trying to figure out the reason why I should learn these things about delegates and protocols. First I thought that it was necessary in order to create nice(er) design of the code. Then I started to read and I cannot really find the reasons I though that I was going to find (That is, "good" reasons...).

When should I apply the delegates and protocols? Practical real life, or just in general good, examples would be usefull (I know the features of protocols and delegates, to some extent at least, so no need to explain that).

Thanks in advance!

A: 

A usage of protocols is to specify an interface for delegates.

A delegate is used to implement what other langages name callbacks.

mouviciel
+2  A: 

Some the best examples can be found within the Cocoa framework.

NSTableView delegate is a great example. The delegate allows the view to be highly customisable without needing to subclass it, but all of the customisation that is provided by the delegate is optional. If this customisation was implemented via subclassing the view would have to become aware of the specifics of the model, which would break the MVC pattern.

The Apple docs are a good read: Cocoa Design Patterns: Delegation

Benedict Cohen
A: 

Another good resource I came across recently is the Stanford University iPhone Application Development course available free of charge via iTunesU (http://itunes.stanford.edu/). In lecture 7 they discuss some best practises for writing your view controllers and introduce the concepts of delegation and protocols.

kharrison
A: 

They're great when one class needs to tell another class that something happened and it should do something.

They help save time that would be spent subclassing while still allowing customization of other classes.

blindJesse
But this is easily achieved by creating a property which you associate with the other object, isn't it? What's the benefit compared to that?
Nicsoft
It's true another class can access the value of the property, but there's no way for a property to notify another class that its value has changed or that some other event has happened.
blindJesse
Could you give some good example when this may be needed?
Nicsoft