委托代理(degegate),顾名思义,把某个对象要作的事情委托给别的对象去作。那么别的对象就是这个对象的代理,代替它来打理要作的事。反映到程序中,首先要明确一个对象的委托方是哪一个对象,委托所作的内容是什么。app
A的头文件:atom
#import <Foundation/Foundation.h> @protocol SecretGardenPicPopViewDelegate <NSObject> @optional - (void)timeTickOut:(BOOL)backToSecret; @end @interface SecretGardenPicPopView : UIView { id<SecretGardenPicPopViewDelegate> _delegate; } @property (nonatomic, assign) id<SecretGardenPicPopViewDelegate> delegate; @end
#import "SecretGardenPicPopView.h" #import "AppDelegate.h" @implementation SecretGardenPicPopView @synthesize delegate = _delegate; - (void)dealloc { self.delegate = nil; [super dealloc]; } - (void)changeTimeTextLabel:(NSTimer *)timer { NSLog(@"===计数===>%d",_timeCount); if (0 <= _timeCount) { _timeLab.text = [NSString stringWithFormat:@"%d''", _timeCount]; } else { [timer invalidate]; NSLog(@"代理===>%p",_delegate); if (_delegate && [_delegate respondsToSelector:@selector(timeTickOut:)]) { //只有当代理存在,且timeTickOut方法被实现的时候才执行下面的语句 NSLog(@"执行代理"); [_delegate timeTickOut:NO]; } } _timeCount -= 1; } @end
B的头文件:spa
#import "SecretGardenPicPopView.h" //A的头文件 @interface SecretGardenController : BaseController<SecretGardenPicPopViewDelegate> //A的代理 @end
B的 .m文件:.net
- (void)timeTickOut:(BOOL)backToSecret { //Do Something }