What Exactly Are Protocols and Delegates and How Are They Used in iOS

What exactly are protocols and delegates and how are they used in IOS?

Protocols are a way to specify a set of methods you want a class to implement if it wants to work with one of your classes. Delegates and Data Sources like UITableViewDelegate and UITableViewDataSource are protocols indeed.

You specify a protocol this way:

@protocol MyProtocol <NSObject>

- (void)aRequiredMethod;

@required
- (void)anotherRequiredMethod;

@optional
- (void)anOptionalMethod;

@end

Methods declared after the @required or before any other specifier are required and the classes that want to use your protocol need to implement all of them. You can also declare some optional methods by declaring them after the @optional specifier.

You then can specify that a class "conforms" to a protocol (implements the required methods) in the interface of the class:

@interface MyClass <MyProtocol>

@end

You usually keep a reference to an object conforming to a protocol using a property. For example, to keep track of a delegate:

@property (nonatomic, weak) id<MyProtocol> delegate;

At this point, in your code, you just have to call the method you want to call on the object that you're keeping reference of and that implements your protocol as you would with any other method:

[self.delegate aRequiredMethod];

To check whether an object conforms to a protocol you can call

[self.delegate conformsToProtocol:@protocol(MyProtocol)]

To check whether an object implements a method you can call

[self.delegate respondsToSelector:@selector(anOptionalMethod)]

For more information, check the Apple's guide Working With Protocols.

Difference between protocol and delegates?

A protocol, declared with the (@protocol syntax in Objective-C) is used to declare a set of methods that a class "adopts" (declares that it will use this protocol) will implement. This means that you can specify in your code that, "you don't care which class is used as long as it implements a particular protocol". This can be done in Objective-C as follows:

id<MyProtocol> instanceOfClassThatImplementsMyProtocol;

If you state this in your code, then any class that "conforms" to the protocol MyProtocol can be used in the variable instanceOfClassThatImplementsMyProtocol. This means that the code that uses this variable knows that it can use whichever methods are defined in MyProtocol with this particular variable, regardless of what class it is. This is a great way of avoiding the inheritance design pattern, and avoids tight coupling.

Delegates are a use of the language feature of protocols. The delegation design pattern is a way of designing your code to use protocols where necessary. In the Cocoa frameworks, the delegate design pattern is used to specify an instance of a class which conforms to a particular protocol. This particular protocol specifies methods that the delegate class should implement to perform specific actions at given events. The class that uses the delegate knows that its delegate coforms to the protocol, so it knows that it can call the implemented methods at given times. This design pattern is a great way of decoupling the classes, because it makes it really easy to exchange one delegate instance for another - all the programmer has to do is ensure that the replacement instance or class conforms to the necessary protocol (i.e. it implements the methods specified in the protocol)!

Protocols and delegates are not restricted only to Objective-C and Mac/iOS development, but the Objective-C language and the Apple frameworks make heavy use of this awesome language feature and design pattern.

Edit:

Here's an example. In the UIKit framework of Cocoa Touch, there is a UITextFieldDelegate protocol. This protocol defines a series of methods that classes which are delegates of a UITextField instance should implement. In other words, if you want to assign a delegate to a UITextField (using the delegate property), you'd better make sure that this class conforms to UITextFieldDelegate. In fact, because the delegate property of UITextField is defined as:

@property(nonatomic, weak) id<UITextFieldDelegate> delegate

Then the compiler will give warnings if you assign a class to it that doesn't implement the protocol. This is really useful. You have to state that a class implements a protocol, and in saying that it does, you're letting other classes know that they can interact in a particular way with your class. So, if you assign an instance of MyTextFieldDelegateClass to the delegate property of UITextField, the UITextField knows that it can call some particular methods (related to text entry, selection etc.) of your MyTextFieldDelegateClass. It knows this because MyTextFieldDelegateClass has said that it will implement the UITextFieldDelegate protocol.

Ultimately, this all leads to much greater flexibility and adaptability in your project's code, which I'm sure you'll soon realise after using this technology! :)

How do I know when to use protocols and delegates, and what are they? ( swift 4.2 )

Protocol:

Think of a protocol as a lingo. It's a specialized vocabulary that objects use to talk to each other. A protocol defines a set of methods and properties that any object that "conforms" to that protocol is guaranteed to have.

Imagine a short-order cook. The short order cook knows the lingo of the restaurant. "I need a #7, well, with everything but onions."

The wait staff doesn't need to know who is working that night. They just place their orders, and the cook cooks them. In fact, the cook doesn't even need to be human. If you could build a robot who understood and could follow the short-order-cook protocol, and could cook the food, you could replace the human with the robot, and the wait-staff wouldn't need to change how they worked at all.

A protocol is very much like that.

Delegates use protocols, but that's not the only way they are used.



Delegate:

A delegate is an object that does a specific job, and that is guaranteed to understand a specific protocol. In the example above, the short-order-cook is the delegate of the restaurant. You don't know what a delegate object is - you just know that it knows how to cook food. You could replace the short order cook with a different short-order cook, and everything works exactly the same as long as they both conform to the short-order-cook protocol. (A delegate is usually defined as an object that conforms to a protocol rather than being a specific class.)

A delegate can also be an object that is used to customize the behavior of another object. For UITableViews, for example, the delegate does things like specify the row height for cells, determines which cells can be selected, handles selection actions, provides header/footer views, and stuff like that.

You frequently provide a delegate to customize the behavior of complex Apple UI objects like table views.

Understanding the Relation Between Delegation and Protocols

1- Is delegation just a way to let the compiler know where to look for the code that will be manipulating the object (UITableView etc.)?

No, delegation is a design pattern. It's just a concept.

2- Do delegation and protocols work together?

Yes they work well together and it's probably the best practice to use protocol for your delegate.

3- Can delegation exist without protocols? If yes, can you show me an example.

Yes you can. Delegation concept is just to remove intellect of an object and put it in the delegate. For exemple an UITableView does not know how many row it has, or what to do when a cell is clicked, so it asks to its delegate.
But the delegate is still another object.

It's better if it implements a particular protocol, but you can do it without.

For exemple :

I've a MyView that is a subview of a MyCustomViewController.

MyCustomViewController.h

- (void)myViewIsTouched;

MyView.h

@property (nonatomic, weak) MyCustomViewController *delegate

MyView.m

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.delegate myViewIsTouched];
}

There is no protocol in this exemple, but it's still a delegate.
(A better way is still using a protocol instead of declaring the method in the .h)

4- When we declare a protocol and a class conforms to it, can we say that this class conforming to the protocol is delegating on behave of the protocol?

I'm not sure about what're saying. But protocols and delegate are not the same thing. An object implementing a protocol does not mean that it's a delegate.

Delegate vs Protocol

A protocol is an interface that a class can conform to, meaning that class implements the listed methods. A class can be tested for conformance to a protocol at compile-time and also at run-time using the conformsToProtocol:.. NSObject method.

A delegate is a more abstract term that refers to the Delegation Design Patten. Using this design pattern, a class would have certain operations that it delegates out (perhaps optionally). Doing so creates an alternative to subclassing by allowing specific tasks to be handled in an application-specific manner, which would be implemented by a delegate.

They are related terms because you often see a Protocol created for the purpose of delegation. If I wanted to allow a delegate to sort something, I'd create a Protocol with a required method listed such as "sortMyCoolStuff:.." and I would require the delegate to implement it. That way, within class that supports calling to a delegate, I can accept a pointer to a delegate and then can say "if that delegate conforms to myCoolProtocol, I know it implements sortMyCoolStuff, so it's safe to call that method instead of doing my built in behavior"

What is the purpose of an iOS delegate?

Delegation is a design pattern not only used in iOS but many other languages. It enables you to hand values and messages over in your class hierarchy.

What exactly does delegate do in xcode ios project?

It's a key concept to understand conceptually so getting your head around how to think about it ahead of the technical details is important. Simply put, a delegate is a callback.

Two main scenarios to use delegates:

  1. A class or control wants to abstract out the details on how to do work (like retrieve data).
  2. Allow others to hook code into a pipeline.

Examples:
UITableView - a table view is just a control that knows how to render a list of cells. It handles all the heavy lifting of rendering, scrolling, etc... But, it has no idea how to load your data. So you implement a datasource delegate which has methods to get the cell data for a given row etc... That makes it easy on you. You just use the control and plug in the specifics for your data. The UITableView will do everything for you ... just answer a few specific questions for. A delegate answers those few specific questions.

A text control - you add a text control to your view and voila! you can type in it and alls good. But what if you want to do something when they start typing or when they're done typing? Well, the text control offers a delegate with methods that allow you to hook into the execution pipeline of the text control. It allows the text control to do everything for you and allows you to interject code where you need it. Many times, there's way to interject code to make a decision on whether something is allowed. The control will call back and ask, should I be able to do x? You can interject code and influence the behavior.

If you're creating a control or class, you can create your own protocol, datasource delegates etc... so your control can focus on doing what's advertised. For example, let's say you wanted to create a task control. You could:

First, create a contract. Hey, if you're going to provide data for my control, these are the questions I'm going to ask you. I'll take it from there... In this case, I'm going to ask you the number of tasks and I'm going to have you give me a task given the row number.

@protocol XXTaskBoardDelegate <NSObject>
-(NSInteger*)getTaskCount;
-(XXTask*)getTaskForRow:(NSInteger*)rowNumber;
@end

In the control or class, give the consumer a way to give us the delegate datasource class that will answer the questions the control will ask. At this point, the control is a pure control. It knows nothing about how you get your data. It's asking for an object (id) that implements a contract/protocol. id

@implementation XXTaskBoard
- (void)setDelegate:(id<XXTaskBoardDelegate>)newDelegate
{
// the control stores the delegate so it can callback and ask you questions.
}

Then, for the delegate class, in the header declare you implement that formal protocol
and in the implementation m file you provide the code.

@interface AppController : NSObject<XXTaskBoardDelegate> 
{
//...
}

then, implement it in the implementation

@implementation AppController
- (NSInteger*)getTaskCount
{
return [model queryTaskCount];
}

- (XXTask*)getTaskForRow:(NSInteger*)rowNumber
{
return [[model tasks] getItem:(NSInteger*)rowNumber];
}

What is a delegate in Objective C's iPhone development?

See this discussion

A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three common delegates:

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

One or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.



Related Topics



Leave a reply



Submit