ios开发之delegate那点事儿

来源:互联网 发布:怎样的穿着叫淘宝风 编辑:程序博客网 时间:2024/05/02 01:50

首先,让我们看看为什么要使用delegate。

一个典型的ios应用程序会有各种类型的对象:windows,tables,buttons,input boxes等等。在一个特定的应用程序中,你会让每个对象做特定的事情。比如说当用户点击一个按钮的时候,会执行一个特定的操作或者使用一个table显示特定的数据。

每个对象实例会有处理特定的事情。比如说我们有一个UITableView的实例,我们可能会让它以特定的方式来显示特定的 数据,同样的,我们对table的每一行进行tapping或者swiping操作的时候,它们也会做出自己特有的事件处理方式。

为了避免为达到某一个特定的目的(actions or events)而创建一个子类(如果有多种不同的特定目的就会创建多个子类),你可以写出响应这些操作或者事件的方法,它们会在这些操作或者事件发生的时候被调用,为了达到此目的,你只需要给这个对象一个delegate(一个对象)。你可以使一个类作为其他一个对象或者多个对象的delegate。

下面是ios开发中一些常见的delegate:

1. The application delegate. The application delegate(UIApplicationDelegate) 通常是这个类自身,具有唯一性,它响应所有与应用程序相关的事件,比如 starting up, shutting down, going into the background。 当你创建一个新的项目文件时,Xcode会自动创建一个app delegate,delegate 中 application: didFinishLaunchingWithOptions: 方法是对应用程序进行第一步设定的地方。

2. UIView subclass delegate. UIView 的许多子类代表各种特定的view对象,包括 UIScrollView, UITextField, UISearchBar等等,它们使用delegates 来响应用户滑动视图,改变 textField 的事件等,常用的:UIScrollViewDelegate, UIAlertViewDelegate, UITextFieldDelegate 和 UITableView delegates。

3. UITableViewDelegate 和 UITableViewDataSource。UITableViewDelegate的Optional 方法用来操作selections,配置section的headings和footers,删除和重新排列cells以及其他操作,它主要用于控制UITableView的视图展现形式。UITableViewDataSource充当的是应用程序数据和UITableView之间的桥梁。它提供了UITableView对象需要显示的数据。


在使用delegate时,声明一个delegate属性需使用 assign 而不是 retain,这样是为了避免产生 retain cycle.

在设定delegate对象的那个类的 dealloc 消息中需要将delegate 置为 nil,这样是为了避免向一个 dealloc 的 delegate 发送消息。



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.

原创粉丝点击