如何理解 Objective-C Delegate
例如,我們要在一個 ViewController 中使用一個ActionSheet,代碼如下:
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Delegate Example"delegate:self // telling this class to implement UIActionSheetDelegatecancelButtonTitle:@"Cancel"destructiveButtonTitle:@"Destructive Button"otherButtonTitles:@"Other Button",nil[actionSheet showInView:self.view];中間的代碼: delegate:self 來告訴當前這個ViewController 來實現 UIActionSheetDelegate
這樣做的原因是
ViewController 和 ActionSheet 二者是相互獨立的,但是當用戶點擊了 ActionSheet 上的按鈕時,ViewController 需要處理 ActionSheet 上按鈕的點擊事件,這樣做相當于通知 ViewController 監聽 UIActionSheetDelegate,以便我們處理 ActionSheet 上按鈕的點擊事件。
注意:
delegte:self; 這行代碼僅是告訴 ViewController 實現 UIActionSheetDelegate,但是我們還需要告訴類實現 UIActionSheetDelegate protocol (協議),方法是在 .h 文件中 加入,如下所示:
- 我們自己創建的類 (CustomClass),如何使用 delegate
在CustomClass.h 文件中 首先要為這個 delegate 定義 protocol (寫在 @interface 之前)
在 protocol 和 end 之間定義 protocol 方法, 這個方法可以被任何使用這個代理的類所使用
.m 文件中沒什么特別的,最重要的要實現 helloDelegate 方法
-(void)helloDelegate {// send message the message to the delegate![delegate sayHello:self]; }接下來我們切換到要使用這個類的 ViewController ,實現上面剛剛創建的 delegate
// DelegateExampleViewController.h // import our custom class#import "CustomClass.h"@interface DelegateExampleViewController : UIViewController <CustomClassDelegate> {} @end在 DelegateExampleViewController.m 文件中,我們需要初始化這個 custom Class,然后讓 delegate 給我們傳遞一條消息
//DelegateExampleViewController.mCustomClass *custom = [[CustomClass alloc] init];// assign delegate custom.delegate = self; [custom helloDelegate];還是在 DelegateExampleViewController.m 我們要實現在 custom Class.h 中生命的 delegate function
-(void)sayHello:(CustomClass *)customClass {NSLog(@"Hi!"); }Bingo!
總結
以上是生活随笔為你收集整理的如何理解 Objective-C Delegate的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql 解锁被锁定的账号
- 下一篇: 如何编程得到数据库信息