代表与协议 [英] Delegate vs Protocol

查看:90
本文介绍了代表与协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

协议和代表之间的区别?

有什么区别议定书和代表之间?

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.

我是Objective-C和Iphone编程的新手。所以请耐心等待。

I am new to Objective-C and Iphone programming. So please bear with me.

推荐答案

协议是类可以符合的接口,这意味着该类实现了列出的方法。可以在编译时以及运行时使用conformsToProtocol:.. NSObject方法测试类是否符合协议。

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.

它们是相关的术语,因为您经常看到为授权而创建的协议。如果我想允许委托对某些内容进行排序,我会创建一个带有所需方法的协议,例如sortMyCoolStuff:..,我会要求委托来实现它。这样,在支持调用委托的类中,我可以接受指向委托的指针然后可以说如果该委托符合myCoolProtocol,我知道它实现了sortMyCoolStuff,所以调用该方法而不是执行我的构建是安全的行为

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"

这篇关于代表与协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆