开发者

Difference between protocol and delegates?

What is the difference between a protocol and a delegate?

and,

How can we declare variables in a protocol开发者_开发百科 class?


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


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: Acting on Behalf of Another Object(Design pattern in oops)

It is a design pattern in which an object called the delegate acts on behalf of, and at the request of, another object.At some point in execution, it sends a message to its delegate; the message tells the delegate that some event is about to happen and asks for some response.The delegate implements the method invoked by the message and returns an appropriate value

An example is the appdelegate object acts on behalf of appobject.

Protocol:Enabling Communication Between Objects Not Related by Inheritance

A protocol is a declaration of a programmatic interface whose methods any class can implement.Protocols are objective c language feature.Simply speaking a list of methods any class can implement.To use this you need to confirm to the protocol. example is UITableviewDatasource protocol,whose methods cellforRowAtIndexPath is declared in the protocol,but we implement it for creating the tableview.

Refer https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/StreamlineYourAppswithDesignPatterns/StreamlineYourApps/StreamlineYourApps.html


We can say Protocol as a set of rules. That rules can be optional or required like we have to use in protocol.

Delegates is a message passing technique in objective C and swift. An object has to take care of that message.

Ex: A simple example that every iOS developer used to is UITableview, While creating a table you must Implement cellForRowAtIndexPath() and numberOfRowsInSection() in your controller, that rules(protocol) are define in UItableview class as required, this is a requires Protocol.

There are other protocol like heightForRowAtIndexPath() which is optional.

Now comes to Delegate in UITableView there is a method(message) didSelectRowAtIndexPath() which sends you a message of an event.If you set the delegate to self it means that your controller is ready to take care of that event.

This terms seems to be more confusing for the developers because we are habitual to used it together(:

Enjoy!!!!


An important prerequisite is understanding protocols first then delegates. I recommend you first see this short tutorial, then see What is a Protocol?. In addition you MUST know the difference between class and protocol so see Objective-C: Class versus Protocol and What is the point of Protocols?.


protocol: is ONLY a blueprint of functions to implement. Any class that adopts that blueprint will have to implement those functions. (Do NOT mistake implementing a function with calling a function)

delegate:1 is for you to also do what a delegat-ing class is doing without inheritance e.g.

For example you have a viewController and want to download images or you want to get customer's distance to a store, so instead of doing it all by yourself, you just have a medium object which does it for you. That object is known as the delegate object. Normally you would do something as such:

class ViewController : UIViewController , DownloaderDelegate{
//other code

// inside viewDidLoad or elsewhere you write:
downloaderHandler.delegate = self // now self can also use whatever the delegating object gives it...previously it was only a viewController but now it's 'almost' also a downloader

very similar to what you do for conforming to a tableViewDelegate

class ViewController : UIViewController , UITableViewDelegate{
//other code

// inside viewDidLoad or elsewhere you write
tableView.delegate = self 

your self can now also do tableView related stuff.


delegate:2 But that object (the delegate) is a plain vanilla object (id or Any). It's dumb! You have to tell it: "Hey for you to work to have specific functionalities you need to conform to the protocol we defined for you. (we aren't going to extend Any or id as that would stupid, (instead) we made a very explicit confined protocol "
in Objective-C it's a pure vanilla id, so you do

 @property (weak) id<DownloaderProtocol>delegate;  

in Swift* it's slightly easier you do :

weak var delegate:DownloaderProtocol?

Protocol comes to rescue...the delegate implements (not use) the function to however it suits the needs of your delegating class.


*: In Swift you don't have id still you don't need its equivalent Any because in Swift protocols are also a first class citizen type


Let see the declaration of delegate in program

 id<myProtocol> *delegatingObject;

The delegatingObject keeps a reference to the other object and at the appropriate time sends a message to that object.

A protocol is a group of related properties and methods that can be implemented by any class.

It implies that any object (id type) that confirms myProtocol (group of related properties and methods) can work as a delegate or you can say any person (id) who has a required degree (protocol) can work as a Teacher (Delegate).


Delegate and Protocol come under the concept of (one to one) communication pattern b/w viewControllers or classes.

This means that one class or viewController is talking to another class or viewController ( Point to remember one to one communication ).m

1st class or viewController gives (delegates) it's reference to the 2nd
class it is talking to, by confirming the protocol of 2nd class.

Using reference of 1st class, 2nd class does the work on behalf of the 1st class and therefore provides information back to the 1st class.

Please watch implementation of the concept using below link : https://www.youtube.com/watch?v=DBWu6TnhLeY.

Formal explanation is - Protocol is a set of methods (either optional or required) that would be implemented by the (1st) class which confirms to that protocol. While, delegate is the reference to that (1st) class which confirms
to that protocol and will adhere to implement methods defined in protocol.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜