iPhone應(yīng)用程序 Delegate使用方法詳解
iPhone應(yīng)用程序 Delegate使用方法詳解是本文要介紹的內(nèi)容,通過(guò)一個(gè)實(shí)例讓我們快速的去學(xué)習(xí),不多說(shuō),我們先來(lái)看內(nèi)容。
先舉一個(gè)例子:
假如"我"的本職工作之一是“接電話(huà)”,但"我"發(fā)現(xiàn)太忙了或來(lái)電太雜了,于是我聘請(qǐng)一位"秘書(shū)"分擔(dān)我“接電話(huà)”的工作,如果電話(huà)是老板打來(lái)的,就讓“秘書(shū)”將電話(huà)轉(zhuǎn)接給“我”。。。
那么,“我”就是A Object. “秘書(shū)”就是"我"的“Delegate”。寫(xiě)成代碼就是 -- [我 setDelegate:秘書(shū)];
delegate的概念出現(xiàn)與mvc(model-view-controller),protocol,單線繼承 密切相關(guān)
- The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.
Cocoa 中處理事件的方式有幾種,其中一種是你可以重載類(lèi)中的對(duì)應(yīng)的事件處理方 法,比如MouseDown事件在NSResponse類(lèi)中就被方法mouseDown:處理,所以所有繼承自NSResponse的類(lèi)都可以重載 mouseDown:方法來(lái)實(shí)現(xiàn)對(duì)MouseDown事件的處理。
另外一種處理方式就是使用Delegate,當(dāng)一個(gè)對(duì)象接受到某個(gè)事件或者通知的時(shí)候, 會(huì)向它的Delegate對(duì)象查詢(xún)它是否能夠響應(yīng)這個(gè)事件或者通知,如果可以這個(gè)對(duì)象就會(huì)給它的Delegate對(duì)象發(fā)送一個(gè)消息(執(zhí)行一個(gè)方法調(diào)用)
協(xié)議 Protocol :
我說(shuō)下我的理解。object-c 里沒(méi)有多繼承。那么又要避免做出一個(gè)對(duì)象什么都會(huì)(super class monster,huge ,super,waste)一個(gè)超能對(duì)象 本身是否定了面向?qū)ο蟮母拍詈驼嬷B了。為了讓代碼更簡(jiǎn)潔,條理更清楚,可以將部分職責(zé)分離。
協(xié)議本身沒(méi)有具體的實(shí)現(xiàn)。只規(guī)定了一些可以被其它類(lèi)實(shí)現(xiàn)的接口。
- @protocal UITextFieldDelegate
- -(BOOL) textFieldShouldReturn:(UITextField *) textField ;
- @end
- @protocal UITextFieldDelegate
- -(BOOL) textFieldShouldReturn:(UITextField *) textField ;
- @end
delegate 總是被定義為 assign @property
- @interface UITextField
- @property (assign) id<UITextFieldDelegate> delegate;
- @end
- @interface UITextField
- @property (assign) id<UITextFieldDelegate> delegate;
- @end
這樣我們就在UITextField內(nèi)部聲明一個(gè)委托(delegate),那么就需要委托的代理實(shí)現(xiàn)UITextFieldDelegate 中約定的行為
- // 首先, 在接口里邊聲明要使用誰(shuí)的Delegate
- @interface delegateSampleViewController : UIViewController
- <UITextFieldDelegate> {}
- @end
- // 然后在實(shí)現(xiàn)文件中初始化的時(shí)候, 設(shè)置Delegate為self(自己)
- @implementation delegateSampleViewController
- // ....
- UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
- textField.delegate = self;//設(shè)置當(dāng)前的控制器為UITextField的代理,相當(dāng)于注冊(cè)(指定)代理人
- [textField becomeFirstResponder];
- [cell.contentView addSubview:textField];
- [textField release];
- // ....
- }
- // 實(shí)現(xiàn)UITextFieldDelegate中約定的行為
- #pragma mark UITextFieldDelegate Method
- // called when 'return' key pressed. return NO to ignore.
- - (BOOL)textFieldShouldReturn:(UITextField *)textField {
- [textField resignFirstResponder];
- return YES;
- }
小結(jié):iPhone應(yīng)用程序 Delegate使用方法詳解的內(nèi)容介紹完了,希望本文讀你有所幫助!