ios 协议和代表之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5431413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:22:32  来源:igfitidea点击:

Difference between protocol and delegates?

iosobjective-cdelegatesprotocols

提问by er.mobileapp

What is the difference between a protocoland a delegate?

aprotocol和 a 和有delegate什么不一样?

and,

和,

How can we declare variablesin a protocol class?

我们如何variables在 a 中声明protocol class

回答by James Bedford

A protocol, declared with the (@protocolsyntax 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:

使用 ( @protocolObjective-C 中的语法)声明的协议用于声明类“采用”(声明它将使用此协议)将实现的一组方法。这意味着您可以在代码中指定“只要实现特定协议,您就不必关心使用哪个类”。这可以在 Objective-C 中完成,如下所示:

id<MyProtocol> instanceOfClassThatImplementsMyProtocol;

id<MyProtocol> instanceOfClassThatImplementsMyProtocol;

If you state this in your code, then any class that "conforms" to the protocol MyProtocolcan 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 MyProtocolwith this particular variable, regardless of what class it is. This is a great way of avoiding the inheritance design pattern, and avoids tight coupling.

如果您在代码中声明了这一点,那么任何“符合”协议MyProtocol 的类都可以在变量instanceOfClassThatImplementsMyProtocol 中使用。这意味着使用这个变量的代码知道它可以使用MyProtocol中定义的任何方法来定义这个特定变量,而不管它是什么类。这是避免继承设计模式和避免紧耦合的好方法。

Delegates are a use of the language feature of protocols. The delegation design patternis 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)!

委托是使用协议的语言特性。该代表团设计模式是一种设计代码以在必要时使用协议的方法。在 Cocoa 框架中,委托设计模式用于指定符合特定协议的类的实例。此特定协议指定委托类应实现的方法,以在给定事件中执行特定操作。使用委托的类知道它的委托符合协议,因此它知道它可以在给定的时间调用已实现的方法。这种设计模式是一种解耦类的好方法,因为它可以很容易地将一个委托实例交换为另一个——程序员所要做的就是确保替换实例或类符合必要的协议(即它实现了协议中指定的方法)!

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.

协议和委托不仅限于 Objective-C 和 Mac/iOS 开发,而且 Objective-C 语言和 Apple 框架大量使用了这种很棒的语言特性和设计模式。

Edit:

编辑:

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

这是一个例子。在 Cocoa Touch 的 UIKit 框架中,有一个UITextFieldDelegate协议。该协议定义了一系列方法,作为UITextField实例的委托的类应该实现这些方法。换句话说,如果你想为UITextField分配一个委托(使用delegate属性),你最好确保这个类符合UITextFieldDelegate。其实是因为UITextField的delegate属性定义为:

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

@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 MyTextFieldDelegateClassto the delegateproperty of UITextField, the UITextFieldknowsthat it can call some particular methods (related to text entry, selection etc.) of your MyTextFieldDelegateClass. It knows this because MyTextFieldDelegateClasshas said that it will implement the UITextFieldDelegateprotocol.

然后,如果您为它分配一个未实现协议的类,编译器将发出警告。这真的很有用。你必须声明一个类实现了一个协议,并且说它实现了,你让其他类知道它们可以以特定的方式与你的类交互。所以,如果你指定的实例MyTextFieldDelegateClassdelegate财产的UITextField,该的UITextField知道,它可以调用一些特定的方法(与文本输入,选择等),您的MyTextFieldDelegateClass。它知道这一点是因为MyTextFieldDelegateClass已经说过它将实现UITextFieldDelegate协议。

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

最终,这一切都会为您的项目代码带来更大的灵活性和适应性,我相信您在使用这项技术后很快就会意识到这一点!:)

回答by NSPratik

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 docfor more detail.

查看此 Apple 文档以获取更多详细信息。

回答by Suraj K Thomas

Delegation: Acting on Behalf of Another Object(Design pattern in oops)

委托:代表另一个对象(oops 中的设计模式)

It is a design patternin 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

它是一种设计模式,其中称为委托的对象代表另一个对象并应另一个对象的请求。该消息告诉该委托,一些事件将要发生,并要求某些response.The委托实现该方法调用由该消息,并返回一个适当的值

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

一个例子是 appdelegate 对象代表 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.

协议是一个编程接口的声明,其方法任何类都可以实现。协议是客观的c语言特性。简单地说,任何类都可以实现的方法列表。要使用它,您需要向协议确认。示例是 UITableviewDatasource 协议,其方法 cellforRowAtIndexPath 在协议中声明,但我们实现它来创建 tableview。

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

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

回答by Honey

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

一个mportant prerequisite是理解协议˚FIRST然后代表。我建议你先看这个简短的教程,然后看 什么是协议?. 此外,您必须知道类和协议之间的区别,因此请参阅Objective-C:类与协议以及协议的重点是什么?.



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

protocol:只是要实现的功能的蓝图。任何采用该蓝图的类都必须实现这些功能。(不要误用调用函数来实现函数)

delegate:1is for you to also dowhat a delegat-ingclass is doing withoutinheritancee.g.

delegate:1是你还什么delegat-ING类是做继承

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:

例如,您有一个 viewController 并且想要下载图像,或者您想要获得客户到商店的距离,因此您不必自己完成所有工作,只需一个中等对象为您完成。该对象称为委托对象。通常你会做这样的事情:

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

与您为符合 tableViewDelegate 所做的非常相似

class ViewController : UIViewController , UITableViewDelegate{
//other code

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

your selfcan now also do tableView related stuff.

self现在也可以做与 tableView 相关的事情。



delegate:2But 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

delegate:2但该对象(委托)是一个普通的普通对象(id 或 Any)。真蠢!您必须告诉它:“嘿,让您工作以拥有符合我们为您定义的协议所需的特定功能。(我们不会扩展 Any 或 id ,因为那会很愚蠢,(相反)我们做了一个很明确的限制协议“
在Objective-C这是一个纯粹的香草id,所以你做

 @property (weak) id<DownloaderProtocol>delegate;  

in Swift*it's slightly easier you do :

在 Swift * 中,你做的稍微容易一些:

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 idstill you don't need its equivalent Anybecause in Swift protocols are also a first class citizen type

*:在 Swift 中你id仍然没有你不需要它的等价物,Any因为在 Swift 协议中也是一等公民类型

回答by Venu Gopal Tewari

Let see the declaration of delegate in program

看看程序中delegate的声明

 id<myProtocol> *delegatingObject;

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

delegatingObject 保持对另一个对象的引用,并在适当的时间向该对象发送消息。

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

这意味着任何确认 myProtocol(相关属性和方法组)的对象(id 类型)都可以作为委托工作,或者您可以说任何具有所需学位(协议)的人(id)都可以作为教师(委托)工作。

回答by guru

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

我们可以说协议是一组规则。该规则可以是可选的或必需的,就像我们必须在协议中使用一样。

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

Delegates是 Objective C 和 swift 中的一种消息传递技术。对象必须处理该消息。

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.

例如:每个 iOS 开发人员曾经使用的一个简单示例是 UITableview,在创建表时,您必须实现,cellForRowAtIndexPath()并且numberOfRowsInSection()在您的控制器中,规则(协议)根据需要在 UItableview 类中定义,这是一个 requires协议

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

还有其他类似的协议heightForRowAtIndexPath()是可选的。

Now comes to Delegatein 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.

现在来到UITableView 中的委托,有一个方法(消息)didSelectRowAtIndexPath()可以向您发送事件消息。如果您将委托设置为 self,则意味着您的控制器已准备好处理该事件。

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

这个术语对于开发者来说似乎更令人困惑,因为我们习惯性地将它一起使用(:

Enjoy!!!!

享受!!!!