How does a delegate work in objective-C?

Josh Bradley picture Josh Bradley · Jun 25, 2009 · Viewed 50k times · Source
  1. Does anyone know where I can find a good explanation/tutorial of what and how an application delegate works in objective-C?
  2. The two books I have don't dwell on delegates enough and do not explain them very well for me to truly understand their power and function.

Answer

Alex Rozanski picture Alex Rozanski · Jun 25, 2009

When in doubt, check the docs!

Basically, delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them, since this makes the design of your application less flexible. Instead of objects controlling one another, they can have a delegate which they send (or delegate) messages to, and the delegate does whatever they do, in order to respond and act to this message, and then usually return something back to the other object.

Delegation is also a better alternative to subclassing. Instead of you having to create your own custom classes to slightly alter the way that other objects behave, or pass them data, delegation allows objects to send messages to their delegates to do work for them without the overhead of creating subclasses to make minor changes to other objects.

Of course, the main disadvantage of delegation is that the delegate methods available are dependent on what the Apple engineers foresee as being useful and what common implementations they expect people to need, which imposes a restriction on what you can achieve. Although, as Quinn Taylor pointed out, this is specific to the Cocoa frameworks and so doesn't apply in all situations.

If delegation is an option over subclassing, then take it, because it's a much cleaner way to manage your code and interactions between objects.