标签:
BoosProtocol.h
#import <Foundation/Foundation.h> //创建协议 @protocol BoosProtocol <NSObject> @required //必须实现的方法 -(NSInteger)buyWood; @optional //可选实现 -(void)text3; @end
WorkeProtocol.h
#import <Foundation/Foundation.h> @protocol WorkeProtocol <NSObject> -(void)salary; @end
Boss.h
#import <Foundation/Foundation.h> #import "BoosProtocol.h" #import "WorkeProtocol.h" @interface Boss : NSObject<WorkeProtocol> //拥有委托权 //必须用weak @property(nonatomic,weak)id <BoosProtocol>delegate; @property(nonatomic,copy)NSTimer*myTime; -(void)wantWood; @end
Boss.m
#import "Boss.h" @implementation Boss - (instancetype)init { self = [super init]; if (self) { /* 第一个参数:时间间隔 第二个参数:实现位置 第三个参数:调用的方法 第四个参数:携带参数 第五个参数:是否可以重复 */ _myTime=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(wantWood) userInfo:nil repeats:YES]; } return self; } -(void)wantWood{ if (_delegate&&[_delegate respondsToSelector:@selector(buyWood)]) { NSInteger n =[_delegate buyWood]; if (n>=100) { //判断定时器是否运行 if ([_myTime isValid]) { [_myTime invalidate]; _myTime=nil; } CFRunLoopStop(CFRunLoopGetCurrent()); } } } -(void)salary{ NSLog(@"表现很好,工资5000,奖金1000"); } @end
Worker.h
#import <Foundation/Foundation.h> #import "BoosProtocol.h" #import "WorkeProtocol.h" //遵守协议 @interface Worker : NSObject<BoosProtocol> @property(nonatomic,assign)NSInteger progress; @property(nonatomic,weak)id<WorkeProtocol>delegate; -(void)getMoney; @end
Worker.m
#import "Worker.h" @implementation Worker - (instancetype)init { self = [super init]; if (self) { _progress=0; } return self; } -(void)getMoney{ if (_delegate&&[_delegate respondsToSelector:@selector(salary)]) { [_delegate salary]; } } //实现协议 -(NSInteger)buyWood{ _progress+=10; NSLog(@"当前进度%zi",_progress); if (_progress>=100) { [self getMoney]; } return _progress; } @end
main.m
/* 代理对象=delegate 代理模式的实现步骤: 1. 创建协议文件,定义协议he方法 2. 代理对象遵循协议 3. 指定代理对象 4. 通过代理调用方法 */ #import <Foundation/Foundation.h> #import "Boss.h" #import "Worker.h" int main(int argc, const char * argv[]) { @autoreleasepool { Boss*boos=[[Boss alloc]init]; Worker*worke=[[Worker alloc]init]; //3.boss指定代理对象worker //一对一 boos.delegate=worke; worke.delegate=boos; //boss提出需求 //通过代理调用方法 //[boss wantWood]; //[[NSRunLoop mainRunLoop] run]; CFRunLoopRun(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/sunbinboke/p/4743176.html