iOS設計模式-委託模式

來源:互聯網
上載者:User

標籤:

 委託是指給一個對象提供機會對另一對象中的變化做出反應或者相應另一個對象的行為。其基本思想是協同解決問題。

在程式中:一般情況下

1.委託需要做的工作有:

     1.1定義協議與方法

    1.2聲明委託變數

     1.3設定代理

     1.4通過委託變數調用委託方法

2.代理需要做的工作有:

     2.1遵循協議

     2.2實現委託方法

下面講解一下使用委託實現頁面傳值的解決方案:

加入我們有兩個ViewController 分別為:ViewController和 TrendViewController

一 .需求:

我們要實現這樣一個功能,當點擊ViewController視圖上的一個按鈕的時候立刻跳轉到TrendViewController,並且把一個String字串傳遞過去。

二.解決方案:

1.在ViewController.h檔案的最上邊聲明協議如下:

@protocol PassTrendValueDelegate-(void)passTrendValues:(NSString *)values;//1.1定義協議與方法@end

2.繼續在ViewController.h中聲明一個委託變數

///1.定義向趨勢頁面傳值的委託變數@property (retain,nonatomic) id <PassTrendValueDelegate> trendDelegate;

3.進入ViewController.m檔案在點擊按鈕事件函數中,設定代理

#pragma mark 點擊趨勢按鈕-(void)trendBtnClick{    //create the view    TrendViewController *trendViewController = [[TrendViewController alloc] initWithNibName:@"TrendViewController" bundle:nil];    self.trendDelegate=trendViewController; //設定代理    [self.trendDelegate passTrendValues:@"abc"];//頁面跳轉 省}

4.進入TrendViewController.h ,引用ViewController的標頭檔,並添加代理協議如下:

#import "ViewController.h"@interface TrendViewController : UIViewController<PassTrendValueDelegate>{}@end

5.實現代理函數:

#pragma <span id="0_nwp" style="width: auto; height: auto; float: none;"><a id="0_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=18&is_app=0&jk=3d222ce8b1c3dc1c&k=mark&k0=mark&kdi0=0&luki=3&n=10&p=baidu&q=69003180_cpr&rb=0&rs=1&seller_id=1&sid=1cdcc3b1e82c223d&ssp2=1&stid=0&t=tpclicked3_hc&td=2116751&tu=u2116751&u=http%3A%2F%2Fwww%2Eandroiddev%2Enet%2Flvesli%5Fdelegate%2F&urlid=0" target="_blank" mpid="0" style="text-decoration: none;"><span style="color:#0000ff;font-size:12px;width:auto;height:auto;float:none;">mark</span></a></span> 實現傳值協議方法-(void)passTrendValues:(NSString *)values{    NSLog(@"values:::%@",values);}

運行一下 OK.

實現頁面傳值的方法還有:

1.通知

2.方法

3.代理方法

4.SharedApplication

5.NSUserdefault

6.通過一個單例的class來傳遞

 

iOS設計模式-委託模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.