分享

关于iOS 委托 代理 协议 的理解

 没原创_去搜索 2016-01-06
http://blog.sina.com.cn/s/blog_65c178a80101hcpm.html


之前一直对这三个词 分不清楚,现经过考究,说一下自己的理解:

协议:
Protocols Define Messaging Contracts
A class interface declares the methods and properties associated with that class. A protocol, by contrast, is used to declare methods and properties that are independent of any specific class.
译:协议用来定义 消息契约 (暂且这么翻译)
一个类接口声明与类相关的方法和属性。一个协议,相比之下,用于声明的方法和属性是独立于任何特定的类。

总结一下:

(1)协议相当于没有与类相关联的接口(网上也有说 协议是一个方法签名的列表 ?注释1),他申明一组方法,列出他的参数和返回值,共享给其他类使用,然后不进行实现,让用它的类来实现这些方法

(2)在任何一个类中,只要声明了协议,都可以实现协议里的方法。

(3)协议不是一个类,且独立于任何特定的类

(4)@protocol关键字声明一个协议


委托:

(来源:http://blog.csdn.net/lovefqing/article/details/8270111)

苹果的官方文档给了很清晰的解释:

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

意译一下就是:代理是一种简单而功能强大的设计模式,这种模式用于一个对象“代表”另外一个对象和程序中其他的对象进行交互。 主对象(这里指的是delegating object)中维护一个代理(delegate)的引用并且在合适的时候向这个代理发送消息。这个消息通知“代理”主对象即将处理或是已经处理完了某一个事件。这个代理可以通过更新自己或是其它对象的UI界面或是其它状态来响应主对象所发送过来的这个事件的消息。或是在某些情况下能返回一个值来影响其它即将发生的事件该如何来处理。代理的主要价值是它可以让你容易的定制各种对象的行为。注意这里的代理是个名词,它本身是一个对象,这个对象是专门代表被代理对象来和程序中其他对象打交道的。

委托是objC中使用非常频繁的一种设计模式,它的实现与协议的使用是分不开的
 
代理:
在设计模式层面上
委托(delegate)也叫代理是iOS开发中常用的设计模式。我们借助于protocol(参考博文:objective-c协议(protocol))可以很方便的实现这种设计模式。
 

注释1:
斯坦福 公开课上关于protocal的解释 如下:
关于iOS <wbr>委托 <wbr>代理 <wbr>协议 <wbr>的理解

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多