views:

5609

answers:

1

Does anyone know where I can find a good explanation/tutorial of what and how an application delegate works in objective-C? 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.

+15  A: 

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.

Perspx
Thanks...I couldn't find anything about delegates in the the man pages earlier when I was looking. Guess I was in the wrong section.
Josh Bradley
You're unlikely to find anything about Objective-C in man pages. Apple's online docs are the definitive source, not only for specifics of cocoa, but also for conceptual background.
Quinn Taylor
@Perspx: I would hesitate to generalize about "the main disadvantage of delegation" in that way — what you're talking about is supplying a delegate for Cocoa code built by Apple. Obviously, there are no limits to what you can do with delegation when you control the delegate interface. I would say the maid disadvantage is that the behavior of the caller is conceptually spread across the delegate, and can change based on which delegate is provided. This is a huge win for flexibility, but can add significant complexity for someone trying to understand the code.
Quinn Taylor
@Quinn Taylor: Yes, changed it. I was talking in context although yes, when talking generally about delegation it doesn't apply.
Perspx