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

思無邪-machengyu發表於2014-05-12

 轉載請註明出處

http://blog.csdn.net/pony_maggie/article/details/25655443

作者:小馬


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

 

這個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];
}

 

原始碼下載地址:

https://github.com/pony-maggie/DelegateDemo

 

 

相關文章