Help in understanding Delegation


#1

I’m still get confused a bit when we talk about delegation. Can someone here help me understand what its role is in objective-c programming?

I understand that it somehow tells the code that it needs to implement a method or something, but how do I best know where and what to delegate?

Is it the Controller in an MVC? or is it an offshoot?

thanks,
Jayson Ng


#2

In a program, objects send messages to each other. They do so because you write code that sends messages. Sometimes, an object gets sent a message and needs to ask for help or tell someone else about this message. This is what delegation is: an object informing/asking another object (the delegate).

Delegation is best learned by example: in this chapter, we learn that a CLLocationManager can have a delegate. And it informs its delegate object when stuff happens to it. For example, when a CLLocationManager produces a new location object, it tells its delegate (“Hey, I found a new location, do what you want to do with this information.”). Later in the book, you will learn about Bonjour and the NSNetServiceBrowser. The NSNetServiceBrowser scans the local area network for servers, when it finds one, it sends a message to its delegate (“Hey, I found a new server, do what you wanna do.”)

A lot of Apple’s classes have delegates. When you first learn delegation, you are sitting on the consumer-end of delegation: you set up some object to be the delegate of an instance of a class that Apple wrote and implement methods from its delegate protocol to be informed of certain events occurring in the delegating object. When you get more comfortable, you end up writing your own classes that delegate out behavior.

It’s one of those design techniques that you have to see and use a few times before you start to understand it. But really, at the end of the day, its a really simple implementation. Pretend you are writing CLLocationManager yourself. The implementation (much simplified):

- (void)startUpdatingLocation
{
      CLLocation *newLocation = [self findNewLocationFromHardware];
      [[self delegate] locationManager:self didUpdateToLocation:newLocation fromLocation:[self previousLocation]];
}

The implementation of delegate methods is done in controller objects typically because there is where you write the application-specific logic.


#3

Hi Joe!

Thanks for this explanation. I think I got it figured out with your explanation.

So a delegate doesn’t do anything until it is asked by another object correct?

thanks,
-Jayson


#4

Correct, the delegate is just sitting there waiting for the delegating object to ask it something.