代理和協議的語法這裏不贅述,自己查資料。
這個demo的思路是這樣的,有一個A類,這個類不是一個基於視圖類,它繼承自NSObject,這個類會啓動一個定時器,當定時器觸發時,它會觸發B視圖彈出一個alert提醒。因爲A類沒法直接操作B視圖,所以它用委託機制,“委託”B視圖來操作。
新建一個view的工程,名爲DelegateDemo,默認生成的這個視圖就是我們的B視圖。然後新建一個timeControl類,作爲我們的A類。
A類的頭文件先要定義一個協議,這個我們的代理要遵循的協議,然後應該還有一個公共的方法,用來啓動定時器,代碼如下:
- #import <Foundation/Foundation.h>
- //協議定義
- @protocol UpdateAlertDelegate <NSObject>
- - (void)updateAlert;
- @end
- @interface TimerControl : NSObject
- //遵循協議的一個代理變量定義
- @property (nonatomic, weak) id<UpdateAlertDelegate> delegate;
- - (void) startTheTimer;
- @end
然後我們看看A類的實現文件,非常簡單,啓動定時器,定時器觸發就通過代理對象更新視圖:
- @implementation TimerControl
- - (void) startTheTimer
- {
- [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(timerProc) userInfo:nil repeats:NO];
- }
- - (void) timerProc
- {
- [self.delegate updateAlert];//代理更新UI
- }
- @end
再來看看視圖類,它首先要遵循上面定義的協議,才能”幫助”A類來處理事情,如下:
- #import <UIKit/UIKit.h>
- #import "TimerControl.h"
- @interface DelegateDemoViewController : UIViewController<UpdateAlertDelegate>
- @end
很明顯,協議在這裏就像中間人的作用,沒有這個中間人,就無法”受理代理”。注意代理和協議並不是總要一起實現,只是大部分情況下我們會用協議來輔助實現代理。B視圖的實現文件也很簡單:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- TimerControl *timer = [[TimerControl alloc] init];
- timer.delegate = self; //設置代理實例
- [timer startTheTimer];//啓動定時器,定時5觸發
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- //"被代理對象"實現協議聲明的方法,由"代理對象"調用
- - (void)updateAlert
- {
- UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"時間到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定",nil];
- alert.alertViewStyle=UIAlertViewStyleDefault;
- [alert show];
- }