BoosProtocol.h
#import <Foundation/Foundation.h>// Create agreement @protocol Boosprotocol < nsobject>@required// methods that must be implemented -(Nsinteger) buywood; @optional// Optional implementation -(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"@interfaceBoss:nsobject<workeprotocol>//have the right to entrust//must be used weak@property (Nonatomic,weak)ID<BoosProtocol>Delegate; @property (nonatomic,copy) Nstimer*MyTime;-(void) Wantwood;@end
Boss.m
#import "Boss.h"@implementationBoss-(instancetype) init{ Self=[Super Init]; if(self) {/*first parameter: time interval The second parameter: implementation position the third parameter: The method called the fourth parameter: Carry parameter fifth parameter: can repeat
*/_mytime=[nstimer Scheduledtimerwithtimeinterval:1target:self selector: @selector (Wantwood) Userinfo:nil Repeats:yes]; } returnSelf ;}-(void) wantwood{if(_delegate&&[_delegate respondstoselector: @selector (Buywood)]) {Nsinteger n=[_delegate Buywood]; if(n>= -) { //determine if the timer is running if([_mytime isValid]) {[_mytime invalidate]; _mytime=Nil; } cfrunloopstop (Cfrunloopgetcurrent ()); } }}-(void) salary{NSLog (@"good performance, salary 5000, bonus");}@end
Worker.h
#import <foundation/foundation.h> #import boosprotocol.h " #import " workeprotocol.h // Compliance Agreement @interface Worker:nsobject<boosprotocol> @property (nonatomic,assign) Nsinteger progress; @property (nonatomic,weak) id <workeprotocol>delegate -(void @end
Worker.m
#import "Worker.h"@implementationWorker-(instancetype) init{ Self=[Super Init]; if(self) {_progress=0; } returnSelf ;}-(void) getmoney{if(_delegate&&[_delegate respondstoselector: @selector (Salary)]) {[_delegate salary]; }}//Implementation Protocol-(Nsinteger) buywood{_progress+=Ten; NSLog (@"Current Progress%zi", _progress); if(_progress>= -) {[Self Getmoney]; } return_progress;}@end
Main.m
/*proxy Object =delegate proxy mode implementation steps: 1. Create the Protocol file, define the protocol he method 2. The proxy object follows protocol 3. Specifying proxy objects 4. Calling methods via proxy*/#import<Foundation/Foundation.h>#import "Boss.h"#import "Worker.h"intMainintargcConst Char*argv[]) {@autoreleasepool {Boss*boos=[[Boss alloc]init]; Worker*worke=[[Worker alloc]init]; //3.boss Specifying agent object worker// one to oneBoos.Delegate=Worke; Worke.Delegate=Boos; //boss puts forward demand//calling methods by proxy//[boss Wantwood]; //[[Nsrunloop Mainrunloop] run];Cfrunlooprun (); } return 0;}
8.ios-protocol