When and how to use protocols and delegates?

Asked

Viewed 2,732 times

7

Could someone please explain to me in what situation and how to use delegates and protocols, I’m a little confused when to what I’ve read around, Thank you!

3 answers

7

Objective-C

In Objective-C there are two types of protocols: Formal and Informal

Informal Protocols

An informal protocol is a category of NSObject usually without implementation, that is, all classes that inherit from NSObject will comply with this informal protocol. Methods in informal protocols are always optional. Informal protocols are an old language resource and have fallen out of use with the addition of @optional in Objective-C 2.0.

But what are categories?

Briefly Category is a way to add methods to existing classes without having to use inheritance. A magic of the categories is that they can be used even in classes that you do not have the source code.

Formal Protocols

A protocol is a kind of agreement that tells which methods a class must implement to comply. In theory a class conforms to a given protocol when it implements all its nonoptional methods. In Cocoa the most common examples of protocols are Delegates and DataSources. Protocols are extremely useful as they help to maintain a low coupling of the classes. Protocols are used to ensure that an object implements certain methods it is necessary to know it.

Delegate

Delegation is a design pattern simple but extremely powerful used when one object acts in place of another or along with it. Delegating an action is asking another object how a certain action should be performed. A classic example of a delegate’s method is the didSelectRowAtIndexPath: of UITableViewDelegate informing that a cell has been selected. Delegation is used when you want to delegate a task or 'ask' something to another object.

Data Source

Data Sources resemble many delegates but serve to provide data for an object. A classic example of a data source method is cellForRowAtIndexPath: also of UITableViewDataSource who expects a UITableViewCell* is returned so that the referenced cell is displayed on the screen.

Swift

In Swift the concept is analogous however informal protocols in Swift are not mentioned anywhere in the documentation. Another extremely interesting thing is that any type can comply with a protocol in Swift with this it is possible to make incredibly intuitive codes with protocols like Equatable, Comparable and Printable.

But what about the categories in Swift?

Swift has something even more magical: Extensions. According to the documentation Extensions allow:

  • Add computed properties and computed static properties
  • Define new instance methods and type methods (yes, we can extend primitive types!)
  • Create new initializers
  • Define subscripts
  • Define and use new nested guys
  • Make an existing type comply with a protocol
  • 1

    Interesting. Thank you!

5


A practical and very common example to be used is when there is a need to come back with data from a view B which was opened by another view a. One of the methods of communication between these two classes, in addition to protocols and delegates, are also the Notifications and KVO (Key-value Observing).

But using your doubt, assuming I have an application in which a first view Formviewcontroller has information to be filled with the coordinates of a map location present in a view Mapviewcontroller, i create my protocol with the definition of a method that returns this information (using Swift, shortly after the Imports):

protocol MapSelectorDelegate {
    func coordinateSelected(coordinate: CLLocation)
}

And a property that will receive the reference for this protocol, the object "delegator":

var delegate: MapSelectorDelegate?

Still in this view, when the coordinate is selected, this is when you execute the method we set in the protocol, when the user touches a point on the map, for example.

delegate.coordinateSelected(coordinate)

The implementation of this method is in the previous class, which I called Formviewcontroller, where we have defined the protocol in the class header:

class FormViewController: UIViewController, MapSelectorDelegate

And assigned as the "delegator" when I pushed "push" the map view through segue:

let mapViewController = segue.destinationViewController as MapViewController
mapViewController.delegate = self

And finally, the implementation of the method delegate, which is mandatory since we do not create it as optional:

func coordinateSelected(coordinate: CLLocation) {
    // Fazer o que quiser com as coordenadas
}
  • Very good explanation. It’s easy to understand with the examples of two views. Thank you!

1

Delegates and MVC of IOS

Delegation, as has been said in other replies is a Pattern design powerful in which one object acts in place or in coordination with another. In Apple’s Model-View-Controller (MVC) delegates are typically controllers and are, in general, used to perform the blind communication of views with your Controller.

The controller has direct access (knows) your Model and Views, but Views and Model do not know your controller, but at certain times need to communicate back with it and do this through blind communication. Model via notification center and views via target-actions (for events such as the touch of a button), and delegates.

When there is more than one MVC (a controller that triggers another controller), this last controller is treated by the first also as a view (that is, the controller treated as view does not know the most external controller and communicates with it through delegate).

How it works

Blind communication causes the view (or object treated as view) to know that it has a delegate, but not exactly its type, and that it can call the methods of that delegate when it needs to. In general the methods that the View will need to call have the sense of DID, SHOULD or WILL. IOS itself uses delegates, for example in one of its views, the Uitextfield. Once this view identifies that the user has just edited it, it calls the method func textViewDidEndEditing(_ textView: UITextView)of your delegate to inform you.

With this mechanism it is simple, for example, "unplug" and "plug" view controllers using storyboard, since they are independent (they do not know the type of their delegate, they only know they have one) and it is possible to use the views in different view-controllers, as in the case of Uitextfield.

Protocols

Protocols are like independent contracts that classes can follow. If a class conforms to a certain protocol, then it needs to implement the required methods indicated in that protocol. The protocols may be used in conjunction with delegates. The object that possesses a delegate knows that it has someone to deal with certain situations (the delegate) but not its type, but knows that this object should be in agreement with a protocol, ie that it implements certain methods and has certain properties.

For example, to make Uitableview as "reusable" as possible, all decisions relating to your data should be delegated to another object (in this case a datasource, which is the same as a delegate but for the purpose of providing data).

A controller that has a View tableView must therefore comply with Uitableviewdatasource Protocol. This indicates that it should implement methods that will be called by tableView as "what is the data for such a cell". If the controller complies with the protocol and does not implement the required methods, then Xcode displays an error.

How to use

Just as Apple uses delegates and protocols to organize its code and make its classes more independent and "reusable" you’re also free to use them. In general, you will use them to ensure blind communication between Views, or objects treated as Views, and your Controller.

Understanding Apple’s MVC becomes clear when using them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.