iPhone應(yīng)用程序 Delegate使用方法詳解
iPhone應(yīng)用程序 Delegate使用方法詳解是本文要介紹的內(nèi)容,通過一個(gè)實(shí)例讓我們快速的去學(xué)習(xí),不多說,我們先來看內(nèi)容。
先舉一個(gè)例子:
假如"我"的本職工作之一是“接電話”,但"我"發(fā)現(xiàn)太忙了或來電太雜了,于是我聘請一位"秘書"分擔(dān)我“接電話”的工作,如果電話是老板打來的,就讓“秘書”將電話轉(zhuǎn)接給“我”。。。
那么,“我”就是A Object. “秘書”就是"我"的“Delegate”。寫成代碼就是 -- [我 setDelegate:秘書];
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 中處理事件的方式有幾種,其中一種是你可以重載類中的對應(yīng)的事件處理方 法,比如MouseDown事件在NSResponse類中就被方法mouseDown:處理,所以所有繼承自NSResponse的類都可以重載 mouseDown:方法來實(shí)現(xiàn)對MouseDown事件的處理。
另外一種處理方式就是使用Delegate,當(dāng)一個(gè)對象接受到某個(gè)事件或者通知的時(shí)候, 會(huì)向它的Delegate對象查詢它是否能夠響應(yīng)這個(gè)事件或者通知,如果可以這個(gè)對象就會(huì)給它的Delegate對象發(fā)送一個(gè)消息(執(zhí)行一個(gè)方法調(diào)用)
協(xié)議 Protocol :
我說下我的理解。object-c 里沒有多繼承。那么又要避免做出一個(gè)對象什么都會(huì)(super class monster,huge ,super,waste)一個(gè)超能對象 本身是否定了面向?qū)ο蟮母拍詈驼嬷B了。為了讓代碼更簡潔,條理更清楚,可以將部分職責(zé)分離。
協(xié)議本身沒有具體的實(shí)現(xiàn)。只規(guī)定了一些可以被其它類實(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 中約定的行為
- // 首先, 在接口里邊聲明要使用誰的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)于注冊(指定)代理人
- [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)容介紹完了,希望本文讀你有所幫助!