iOS开发Delegate,Notification,Block使用心得
(一)简要介绍
1.Delegate(代理、委托)
代理几乎是iOS开发中最常用的传值方式,在项目中的AppDelegate就是使用的这种设计模式,不仅如此,还有很多原生的控件也使用的这种设计模式,比如:UITextFiled,UITableView等等。官方给出的解释如下:
Delegation is a simple and powerful pattern in which one object in a program 1 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.
具体使用方法不再示例(网上关于Delegate基础使用的博文数不胜数示例),主要总结一下Delegate的优点和缺陷。
优点:
>
1.减少代码的耦合性,使事件监听和事件处理相分离。
>
2.清晰的语法定义,减少维护成本,较强的代码可读性。
>
3.不需要创建第三方来监听事件和传输数据。
>
4.一个控制器可以实现多个代理,满足自定义开发需求,可选必选有较大的灵活性。