In ancient Greece, there was a philosopher who did only three things in his life: "Eat", "Sleep", "work". In order to better life and improve the efficiency of the work, he decided to find a disciple, to entrust these things to the Apprentice. To become his apprentice, however, a protocol is required to deal with three things, such as sleeping, eating, and working.
There are three objects involved:
First: Philosophers correspond to a general class Philospher
Second: The protocol corresponds to a philospherdelegate that prescribes three methods of sleep eat work
Third: The Apprentice corresponds to a delegate object Viewcontroller
Entrustment Agreement: PhilospherDelegate.h
@protocol philosopherdelegate@required-(void) sleep;-(void) eat;-(void) work; @end
The delegate agreement does not require a. m file to be defined in other. h files
Delegate class Viewcontroller
#import <UIKit/UIKit.h> #import "PhilosopherDelegate.h" @interface viewcontroller:uiviewcontroller< Philosopherdelegate> @end
#import "ViewController.h" #import "Philosopher.h" @interface Viewcontroller () @end @implementation viewcontroller-( void) viewdidload{ [Super Viewdidload]; Philosopher *obj = [[Philosopher alloc] init]; Obj.delegate = self; [obj start];} -(void) didreceivememorywarning{ [Super didreceivememorywarning]; Dispose of any resources the can be recreated.} #pragma--Philosopherdelegate method implementation-(void) sleep{ NSLog (@ "sleep ...");} -(void) eat{ NSLog (@ "Eat ..."); -(void) work{ NSLog (@ "work ..."); @end
Philosopher philosopher
#import "PhilosopherDelegate.h" @interface philosopher:nsobject{ nstimer *timer; int count;} @property (nonatomic, weak) id<philosopherdelegate> delegate;-(void) start;-(void) handle; @end
#import "Philosopher.h" @implementation philosopher@synthesize delegate;-(void) start{ count= 0; Timer = [Nstimer scheduledtimerwithtimeinterval:3.0 target:self selector: @selector (handle) Userinfo:nil Repeats:yes]; }-(void) handle{ switch (count) {case 0: [self.delegate sleep]; count++; break; Case 1: [self.delegate eat]; count++; break; Case 2: [self.delegate work]; [Timer invalidate]; break; }} @end
IOS Delegate Mode Understanding example