標籤:
委託是指給一個對象提供機會對另一對象中的變化做出反應或者相應另一個對象的行為。其基本思想是協同解決問題。
在程式中:一般情況下
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設計模式-委託模式