iOS.常用设计模式.02.委托模式
WTDelegate
#import <Foundation/Foundation.h> @protocol WTDelegate <NSObject> @required - (void)sleep; - (void)eat; - (void)work; @end
WTPhilosopher.h
#import <Foundation/Foundation.h> #import "WTDelegate.h" @interface WTPhilosopher : NSObject { NSTimer *timer; int count; } @property (nonatomic,weak) id<WTDelegate> delegate; - (void)start; - (void)handle; @end
WTPhilosopher.m
#import "WTPhilosopher.h" @implementation WTPhilosopher @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; default: break; } } @end
WTViewController.m
#import "WTViewController.h" #import "WTPhilosopher.h" @interface WTViewController () @end @implementation WTViewController - (void)viewDidLoad { [super viewDidLoad]; WTPhilosopher *philosopher = [[WTPhilosopher alloc] init]; philosopher.delegate = self; [philosopher start]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma -- WTDelegate 方法实现 -(void) sleep { NSLog(@"sleep..."); } -(void) eat { NSLog(@"eat..."); } -(void) work { NSLog(@"work..."); } @end
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。