委託代理(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 }