What is meant by .delegate=self?
Asked Answered
H

3

48

Could anyone explain the meaning of someViewController.delegate = self and self.delegate? Where do they help us?

Hypothetical answered 18/11, 2010 at 5:27 Comment(0)
E
104

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.

Eleanore answered 18/11, 2010 at 8:47 Comment(6)
Incidentally there is NOT REALLY a neutrino detection delegate. You have to write your own.Eleanore
Great answer. Could you give an example, on the flip side, when it would be necessary (and what it means) to set the delegate to something else? (i.e. what happens when you don't use self)Luong
Sure! You're a "house". You make a "room". The room gets delegate information from something (let's say, a "thermometer"). So essentially, IN "HOUSE", you would make the room, and then you would say "set thermometer delegate to room". OR !!!!! Simply, in the "ROOM," when it is initialised, you could say "set thermometer delegate to self"! It's exactly the same, see! Hope it helps!!Eleanore
What a fantastic explanation - it reminds me of the best teachers I ever had. If you have a moment to spare then I have a new question on a related topic https://mcmap.net/q/357310/-if-duplicate-protocol-definition-of-39-uigesturerecognizerdelegate-39-is-ignored-how-can-i-define-targets/2348597 I'd welcome your response.Unwrap
and what does blah represent?Detachment
@Detachment waking up an older thread but to answer your question, in an example blah is the object for some manager of data. Let's say you have a WeatherManager struct that handles url requests and parsing json data. You'd have to declare that weather = WeatherManager() in your UIViewController class which also implements the methods declared in the protocol WeatherManagerDelegate (& by convention place these within the same file holding the struct that corresponds to the data being handled, which in this case is WeatherManager). So, blah becomes weather and thus weather.delegate = selfLoafer
A
-2

Delegate is used to pass/communicate data/message b/w two objects of classes. Here, tableView(Sender) sends data/message to viewController(Receiver). Consider example of implementing UITableView in custom viewController Here, UITableViewDataSource & UITableViewDelegate are actually protocols. Unfortunately, UIKit Framework is not open source. But I will assure this what internally happens after referring many articles.

Protocol is like basketball coach with some requirements in it. He/She tells players like class, struct, enum what to do? by using those requirements. But He/She doesn't knows how to do?by themself. So, the class or struct which conforms that protocol should provide implementation to those requirements while achieving to dunk the ball.

protocol UITableViewDelegate {
 func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
}

A Protocol is said to be DataSource protocol then it always contains required functions with "return type" as shown below.

protocol UITableViewDataSource {
 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
 func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
}

Implementing UITableView inside custom viewController

class viewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let tableView = UITableView()    

    override func viewDidLoad {
      tableView.delegate = self
      tableView.dataSource = self
    }

Here, tableView acts as Delegator(sender) & viewController object i.e (self) as Delegate(receiver).

In order to get UITableView in viewController.It should to conform to both the Protocols.

So, viewController class object has implemented all those required functions of both the protocols. Now self can be used either as UITableViewDelegate type or UITableViewDataSource type because Protocol can be used as type for an object of class which conforms to it. Now, both properties of tableView i.e delegate & dataSource are assigned to self because its having same respective protocol types.

The non-optional functions of both Protocols are implemented in viewController class object as below

Protocol UITableViewDelegate functions

func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
// Do further processes like pushing or poping another viewController
}

Protocol UITableViewDataSource functions

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
 }

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
 }

1) When the user select a row in a section then tableview(Sender) i.e UItableView() calls the UITableViewDelegate func below shown by passing data to parameters tableView & indexPath which resides in viewController object(Receiver) through its delegate property. Now viewController uses those passed data to do further processes like pushing or poping to new custom viewController.

tableView.delegate?.tableView(UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

2) Functions inside UITableViewDatasource protocol provides custom data to tableview(Sender). The tableview asks the viewController object by calling Datasource functions with passing data to parameters tableView & indexPath which resides in viewController object(Receiver) through its datasource property. Now viewController uses those passed data & returns custom data back tableview. Now tableview uses those data to create "10" cells in a section & kind of "cell" at indexpath

tableView.dataSource?.tableView(UITableView, numberOfRowsInSection section: Int) -> returns "10"

tableView.dataSource?.tableView(UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> returns "cell"

Finally, whole UIKit Framework uses delegate & datasource design patterns in all its classes such as UIApplication, UITableView, UICollectionView, UITextField & so on to communicate data. Unfortunately, UIKit Framework is not open source.

Advection answered 2/1, 2018 at 23:27 Comment(1)
Down voting is for more than just if the answer is incorrect. If you hover over the down vote button you will see a tool tip. I would suggest answering questions that are more recent and don’t have answers already. You can favourite tags and it will filter the list of questions to be more relevant to you. That way you can find newer questions to answer.Homotaxis
C
-3

If in any case Bourne's answer doesn't help .. a delegate is basically the reaction of an event on an object and saying ".delegate=self" means those protocols have been adopted in self ... for eg.. what happens when a row is selected in tableview is told by tableview's delegate method "didSelectRowAtIndexPath" ... and if a viewcontroller has a tableview .. and "didSelectRowAtIndexPath" is defined in that viewcontroller only then we will say ... tableview.delegate = self"... and "self.anything" is used to say that "anything" is a property of self.. for eg. NSString* anything; @property(nonatomic,retain) NSString* anything;

then "self.anything"

Cross answered 18/11, 2010 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.