zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    日期操作
    sanchi
    502 Server dropped connection
    把项目挂载到composer上
    从composer上在本地创建一个项目
    初始化后,composer安装
    在项目目录初始化composer
    Linux安装composer
    linux网络编程之TCP/IP基础
    grep的用法
  • 原文地址:https://www.cnblogs.com/cqchen/p/3775844.html
Copyright © 2011-2022 走看看