轉(zhuǎn)載請注明出處
http://blog.csdn.net/pony_maggie/article/details/25655443
作者:小馬
代理和協(xié)議的語法這里不贅述,自己查資料。
這個demo的思路是這樣的,有一個A類,這個類不是一個基于視圖類,它繼承自NSObject,這個類會啟動一個定時器,當(dāng)定時器觸發(fā)時,它會觸發(fā)B視圖彈出一個alert提醒。因為A類沒法直接操作B視圖,所以它用委托機制,“委托”B視圖來操作。
新建一個view的工程,名為DelegateDemo,默認(rèn)生成的這個視圖就是我們的B視圖。然后新建一個timeControl類,作為我們的A類。
A類的頭文件先要定義一個協(xié)議,這個我們的代理要遵循的協(xié)議,然后應(yīng)該還有一個公共的方法,用來啟動定時器,代碼如下:
[objc]view plaincopy
#import?
//協(xié)議定義
@protocolUpdateAlertDelegate?
-?(void)updateAlert;
@end
@interfaceTimerControl?:?NSObject
//遵循協(xié)議的一個代理變量定義
@property(nonatomic,?weak)id?delegate;
-?(void)?startTheTimer;
@end
然后我們看看A類的實現(xiàn)文件,非常簡單,啟動定時器,定時器觸發(fā)就通過代理對象更新視圖:
[objc]view plaincopy
@implementationTimerControl
-?(void)?startTheTimer
{
[NSTimerscheduledTimerWithTimeInterval:5.0ftarget:selfselector:@selector(timerProc)userInfo:nilrepeats:NO];
}
-?(void)?timerProc
{
[self.delegateupdateAlert];//代理更新UI
}
@end
再來看看視圖類,它首先要遵循上面定義的協(xié)議,才能”幫助”A類來處理事情,如下:
[objc]view plaincopy
#import?
#import?"TimerControl.h"
@interfaceDelegateDemoViewController?:?UIViewController
@end
很明顯,協(xié)議在這里就像中間人的作用,沒有這個中間人,就無法”受理代理”。注意代理和協(xié)議并不是總要一起實現(xiàn),只是大部分情況下我們會用協(xié)議來輔助實現(xiàn)代理。B視圖的實現(xiàn)文件也很簡單:
[objc]view plaincopy
-?(void)viewDidLoad
{
[superviewDidLoad];
//?Do?any?additional?setup?after?loading?the?view,?typically?from?a?nib.
TimerControl*timer?=?[[TimerControlalloc]init];
timer.delegate=self;//設(shè)置代理實例
[timerstartTheTimer];//啟動定時器,定時5觸發(fā)
}
-?(void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
//?Dispose?of?any?resources?that?can?be?recreated.
}
//"被代理對象"實現(xiàn)協(xié)議聲明的方法,由"代理對象"調(diào)用
-?(void)updateAlert
{
UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"提示"message:@"時間到"delegate:selfcancelButtonTitle:nilotherButtonTitles:@"確定",nil];
alert.alertViewStyle=UIAlertViewStyleDefault;
[alertshow];
}