Possible Duplicate:
Difference between protocol and delegates?
Is there any difference between Protocol and Delegates?
If they are same why do we need two doing the same?
When to use Delegate and when to use Protocol.
I am new to Objective-C and Iphone programming. So please bear with me.
Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol. Have a look at this Apple doc for more detail.
Delegation can be used to respond to a particular action, or to retrieve data from an external source without needing to know the underlying type of that source. Apple notes that: A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
How will you explain the difference between delegate and protocol in Swift? Protocol: A set of methods that would be implemented by the class which conforms to that protocol. Delegate: The reference to that class which conforms to the protocol and will adhere to implement methods defined in the protocol.
In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behavior of another object.
Protocols and delegates are two related but different concepts:
On the one hand, protocols declare methods that can be implemented by any class. These classes are said to conform to the protocol. They are like interfaces in Java. Protocols can be formal or informal:
Formal protocols are declared with a @protocol
block.
Informal protocols can be implemented in terms of a @protocol
block with all the methods being @optional
or with a category of NSObject
.
On the other hand, delegation is a design pattern by which an object is given an opportunity to react to changes in another object or influence its behaviour. The basic idea is to get two objects to coordinate to solve a problem while minimizing coupling between these two objects and avoiding subclassing. Subclassing creates a tight coupling between the subclass and its superclass whereas delegation creates a much looser relationship based on anonymous objects.
This pattern is typically implemented by the means of a protocol or to put it in another way, a delegate is typically an anonymous object that conforms to a protocol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With