What is meant by .delegate=self?

Delegates send messages to you.

For example: if you use the accelerometer delegate, you will get messages about the accelerometer.

If you use that new neutrino-detection delegate, you will get messages about any neutrinos detected in the area.

If you use PopUps, PopUps send you messages. And the way that is done, is with the PopUp’s delegate. There are many, many examples.

So, delegates send messages.

It’s that simple.

You might ask, “WHERE does it send these messages?”

The answer is this: it sends the messages to where you set the “.delegate” thingy.

When you “set the delegate,” what you are doing is saying where you want the messages to go.

Hence,

blah.delegate = amazingPlace will send the messages to “amazingPlace”.

blah.delegate = somewhereElse will send the messages to “somewhereElse”.

blah.delegate = self will send the messages …… to you.

Very often, you want the messages to come to “you”, so you just say “blah.delegate = self”

It is a very common mistake, to forget that line of code.

If you forget that line of code, you are stuffed. The messages go nowhere, and you are left scratching your head trying to figure out what went wrong.

Something else you have to do: when you use a delegate, you have to announce beforehand, that, you want to use the delegate.

How to do that?

It’s very easy…

In the old days with Objective-C…

// old days!
@interface AppDelegate_Pad : NSObject <UIApplicationDelegate>
@interface BigTop : UIViewController <ASIHTTPRequestDelegate,
                                        UIPopoverControllerDelegate>
@interface Flying : UIViewController <UIAccelerometerDelegate>

You can see that ‘BigTop’ wants to use two delegates, namely the ASIHTTPRequestDelegate and the UIPopoverControllerDelegate. Whereas ‘Flying’ only wants to use one delegate – it wants to use the accelerometer.

In Swift…

 class YourClass:UIViewController, SomeDelegate, AnotherDelegate

You can’t really do much on the iPhone without using delegates all over the place.

Delegates are used everywhere and all the time in iOS.

It is perfectly normal that a class might use a dozen delegates. That is to say, your class will want to get messages from a dozen delegates.

Nowadays with Swift you simply type

  blah.delegate = self

and that’s all there is to it.

So that’s what you’re doing. Delegates send messages. You have to say where you want the messages to go. Very typically, you want them to go to “you,” so in that case you simply say blah.delegate=self.

Leave a Comment