Difference Between Protocol and Delegates

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 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 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! :)

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 

- (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 

@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 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.

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 difference between Notifications, Delegates, and Protocols?

You can find answers by searching in stackoverflow ...

  • Delegates and notifications
  • Protocoles and delegates

What is the difference between Delegate and Notification?

Short Answer: You can think of delegates like a telephone call. You call up your buddy and specifically want to talk to them. You can say something, and they can respond. You can talk until you hang up the phone. Delegates, in much the same way, create a link between two objects, and you don't need to know what type the delegate will be, it simply has to implement the protocol. On the other hand, NSNotifications are like a radio station. They broadcast their message to whoever is willing to listen. The radio station can't receive feedback from it's listeners (unless it has a telephone, or delegate). The listeners can ignore the message, or they can do something with it. NSNotifications allow you to send a message to any objects, but you won't have a link between them to communicate back and forth. If you need this communication, you should probably implement a delegate. Otherwise, NSNotifications are simpler and easier to use, but may get you into trouble.

Long Answer:

Delegates are usually a more appropriate way of handling things, especially if you're creating a framework for others to use. You gain compile time checking for required methods when you use protocols with your delegates, so you know when you compile if you're missing any required methods. With NSNotificationCenter you have no such guarantee.

NSNotificationCenter is kind of "hack-ish" and is frequently used novice programmers which can lead to poor architecture. A lot of times these two features are interchangeable, but more "hardcore" developers might scoff at the use of the NSNotificationCenter.


Q: what is the reason for using "id" and what is the difference of them?

A: Using id allows you to send any object to the method as a parameter. Note that you can not send primitives such as bools, floats, doubles, ints, etc. unless they are wrapped in their respective Object wrappers.


classB{

-(void)DelegateMethod;

}

and then call this in

classA{

classB delegate;

-(void)viewdidload{

[self.delegate DelegateMethod];

}

}

The above example you provided would require that classA's delegate always be of type classB, which isn't advantageous. Instead of using delegates in this scenario, you would probably just use a variable that referred to your other class, say, myClassB. The beauty of delegates is that you can pass around any object, and the code just works as long as they implement the required methods (which the compiler ensures, as long as it's marked as the correct delegate type).

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.

Delegation in iOS without a protocol?

A delegate doesn't have to conform to a protocol. You can code to an implementation, but that is bad practice.

I think apple are saying that this is the way things are normally done. You don't have to use protocols...but you should if you want to keep things flexible.

Delegation is in essence asking someone else to do something for you. If you enforce a contract, then its more likely they will do it for you.

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.



Related Topics



Leave a reply



Submit