转载请注明出处
作者:小马
代理和协议的语法这里不赘述,自己查资料。
这个demo的思路是这样的,有一个A类,这个类不是一个基于视图类,它继承自NSObject,这个类会启动一个定时器,当定时器触发时,它会触发B视图弹出一个alert提醒。因为A类没法直接操作B视图,所以它用委托机制,“委托”B视图来操作。
新建一个view的工程,名为DelegateDemo,默认生成的这个视图就是我们的B视图。然后新建一个timeControl类,作为我们的A类。
A类的头文件先要定义一个协议,这个我们的代理要遵循的协议,然后应该还有一个公共的方法,用来启动定时器,代码如下:
[objc]
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]
1. @implementation TimerControl
2.
3.
4. - (void) startTheTimer
5. {
6.
7. 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]
1. #import <UIKit/UIKit.h>
2. #import "TimerControl.h"
3.
4. @interface DelegateDemoViewController : UIViewController<UpdateAlertDelegate>
5.
6. @end
很明显,协议在这里就像中间人的作用,没有这个中间人,就无法”受理代理”。注意代理和协议并不是总要一起实现,只是大部分情况下我们会用协议来辅助实现代理。B视图的实现文件也很简单:
[objc]
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. .delegate = self; //设置代理实例
7. 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. .alertViewStyle=UIAlertViewStyleDefault;
22. show];
23. }
源码下载地址:
https://github.com/pony-maggie/DelegateDemo