开发者

Applied delegating and protocols

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开发者_如何学JAVA 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!


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


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

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜