日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何理解 Objective-C Delegate

發布時間:2023/12/10 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何理解 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 文件中 加入,如下所示:

@interface DelegateExampleViewController : UIViewController <UIActionSheetDelegate>
  • 我們自己創建的類 (CustomClass),如何使用 delegate

在CustomClass.h 文件中 首先要為這個 delegate 定義 protocol (寫在 @interface 之前)
在 protocol 和 end 之間定義 protocol 方法, 這個方法可以被任何使用這個代理的類所使用

#import @class CustomClass;//為Delegate 定義 protocol @protocol CustomClassDelegate //定義 protocol 方法 -(void)sayHello:(CustomClass *)customClass; @end@interface CustomClass : NSObject {}// define delegate property @property (nonatomic, assign) id delegate;// define public functions -(void)helloDelegate;@end

.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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。