IOS學習之一個示例弄懂代理(delegate)和協議

代理和協議的語法這裏不贅述,自己查資料。

 

這個demo的思路是這樣的,有一個A類,這個類不是一個基於視圖類,它繼承自NSObject,這個類會啓動一個定時器,當定時器觸發時,它會觸發B視圖彈出一個alert提醒。因爲A類沒法直接操作B視圖,所以它用委託機制,“委託”B視圖來操作。

 

新建一個view的工程,名爲DelegateDemo,默認生成的這個視圖就是我們的B視圖。然後新建一個timeControl類,作爲我們的A類。

 

A類的頭文件先要定義一個協議,這個我們的代理要遵循的協議,然後應該還有一個公共的方法,用來啓動定時器,代碼如下:

 

[objc] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. #import <Foundation/Foundation.h>  
  2.   
  3.   
  4. //協議定義  
  5. @protocol UpdateAlertDelegate <NSObject>  
  6. - (void)updateAlert;  
  7. @end  
  8.   
  9.   
  10. @interface TimerControl : NSObject  
  11. //遵循協議的一個代理變量定義  
  12. @property (nonatomic, weak) id<UpdateAlertDelegate> delegate;  
  13.   
  14. - (void) startTheTimer;  
  15.      
  16. @end  


然後我們看看A類的實現文件,非常簡單,啓動定時器,定時器觸發就通過代理對象更新視圖:

[objc] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. @implementation TimerControl  
  2.   
  3.   
  4. - (void) startTheTimer  
  5. {  
  6.   
  7.     [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(timerProc) userInfo:nil repeats:NO];  
  8. }  
  9.   
  10. - (void) timerProc  
  11. {  
  12.     [self.delegate updateAlert];//代理更新UI  
  13. }  
  14.   
  15. @end  


再來看看視圖類,它首先要遵循上面定義的協議,才能”幫助”A類來處理事情,如下:

[objc] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. #import <UIKit/UIKit.h>  
  2. #import "TimerControl.h"  
  3.   
  4. @interface DelegateDemoViewController : UIViewController<UpdateAlertDelegate>  
  5.   
  6. @end  


很明顯,協議在這裏就像中間人的作用,沒有這個中間人,就無法”受理代理”。注意代理和協議並不是總要一起實現,只是大部分情況下我們會用協議來輔助實現代理。B視圖的實現文件也很簡單: 

 

[objc] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     // Do any additional setup after loading the view, typically from a nib.  
  5.     TimerControl *timer = [[TimerControl alloc] init];  
  6.     timer.delegate = self//設置代理實例  
  7.     [timer startTheTimer];//啓動定時器,定時5觸發  
  8. }  
  9.   
  10. - (void)didReceiveMemoryWarning  
  11. {  
  12.     [super didReceiveMemoryWarning];  
  13.     // Dispose of any resources that can be recreated.  
  14. }  
  15.   
  16. //"被代理對象"實現協議聲明的方法,由"代理對象"調用  
  17. - (void)updateAlert  
  18. {  
  19.     UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"時間到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定",nil];  
  20.       
  21.     alert.alertViewStyle=UIAlertViewStyleDefault;  
  22.     [alert show];  
  23. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章