IOS學習之一個示例弄懂代理(delegate)和協議
轉載請註明出處
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
相關文章
- iOS開發中不想用delegate協議方法怎麼辦?iOS協議
- iOS Swift 建立代理協議的多種方式iOSSwift協議
- 徹底弄懂C#中delegate、event、EventHandler、Action、Func的使用和區別C#
- Raft協議學習筆記Raft協議筆記
- Raft 協議學習筆記Raft協議筆記
- BGP路由協議學習一路由協議
- 學習筆記 - DNS協議筆記DNS協議
- IP協議學習筆記協議筆記
- 什麼是代理協議?協議
- TCP/IP學習筆記之協議和郵件TCP筆記協議
- 網路協議之:haproxy的Proxy Protocol代理協議協議Protocol
- 使用wireshark學習網路協議協議
- Internet安全協議 學習筆記協議筆記
- Python學習之迭代器協議Python協議
- OAuth 2.0 協議學習筆記OAuth協議筆記
- Raft協議和ZAB協議Raft協議
- Swift代理協議的安全使用Swift協議
- ESP32藍芽學習--GATT協議學習藍芽協議
- [iOS] 從 application delegate 引申三點iOSAPP
- 認證授權:學習OAuth協議OAuth協議
- HTTP協議學習---(三)進階篇HTTP協議
- Dubbo原始碼學習--Rmi協議(八)原始碼協議
- iOS開發- tableView的協議iOSView協議
- 系統學習iOS動畫之一:檢視動畫iOS動畫
- CC2530 ZigBee協議棧 學習心得協議
- CAN匯流排協議 學習筆記協議筆記
- RTMP協議學習——Message與Chunk解讀協議
- 網路基礎 Modbus協議學習總結協議
- Socks協議以及代理轉發工具分析協議
- Gossip協議和Grpc協議的區別Go協議RPC
- WiFi協議曝安全漏洞:Linux、Android和iOS未能逃脫WiFi協議LinuxAndroidiOS
- 淺談WebSocket協議、WS協議和WSS協議原理及關係Web協議
- 計算機網路學習筆記(10) TCP/IP協議棧 之TELNET協議計算機網路筆記TCP協議
- ZigBee ZStack 協議棧學習--架構分析篇協議架構
- 無線網際網路協議802.11學習協議
- HTTP協議和MQTT協議對比誰更好HTTP協議MQQT
- HTTP協議和HTTPS協議的異同點?HTTP協議
- 五個給機器學習和資料科學入門者的學習建議機器學習資料科學
- QT使用 http 協議通訊的實現示例QTHTTP協議