• ObjectiveC学习之旅(八)代理设计模式


    一、协议的具体用法

      协议的具体用法就是使用代理。代理设计模式相当于C#当中的委托。

    二、如何实现代理

      这里介绍一个案例

    三、代理两端如何通讯

      代理两段的通讯业就是说代理端和被代理端如何通讯的。

    四、调用前后顺序的问题

    如果说你要调用一个协议,但是你在调用的时候你的协议还没有声明,所以程序会报错,解决办法有2个,第一,可以在前面声明一下,例如:@protocol DogBark;放在#import <Foundation/Foundation.h>下面。第二,前向声明可以声明类,例如,class Dog; 如果我们把协议声明放到了前面,但是类的声明在我们声明的后面,那样又会报错,所以解决办法是我们在前面加一个类的声明。

    五、demo

    dog.m

    View Code
    #import "Dog.h"
    
    @implementation Dog
    @synthesize ID = _ID;
    @synthesize delegate;
    
    - (id) init
    {
        self = [super init];
        if (self) {
            timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
            // 创建一个定时器 每个1.0s就调用 [self updateTimer:nil];
        }
        return self;
    }
    - (void) updateTimer:(id)arg
    {
        barkCount++;
        NSLog(@"dog bark %d", barkCount);
        // 通知狗的主人
        // delegate;
        [delegate bark:self count:barkCount];
        // 调用delegate里面的 bark:count: 方法
        // 向主人回报
    }
    
    @end

    dog.h

    View Code
    #import <Foundation/Foundation.h>
    @class Dog;
    // @class表示前向申明一个类
    
    // 定义一个人和狗通讯的方式 protocol
    @protocol DogBark <NSObject>
    - (void) bark:(Dog *)thisDog count:(int)count;
    @end
    
    @protocol DogBark;
    // @protocol表示 协议前向申明
    
    @interface Dog : NSObject
    {
        NSTimer *timer;
        int barkCount;
        
        int _ID;
        
        id <DogBark> delegate; // ownner 狗的主人
    }
    @property int ID;
    @property (assign) id <DogBark> delegate;
    
    @end

    Person.m

    View Code
    #import "Person.h"
    
    @implementation Person
    
    @synthesize dog = _dog;
    
    - (void) setDog:(Dog *)dog
    {
        if (_dog != dog) {
            [_dog release];
            _dog = [dog retain];
            // 通知_dog的主人是 self
            [_dog setDelegate:self];
        }
    }
    - (Dog *) dog
    {
        return _dog;
    }
    
    - (void) bark:(Dog *)thisDog count:(int)count
    {
        // 当狗叫的时候来调用 xiaoLi人的这个方法
        NSLog(@"person this dog %d bark %d", 
              [thisDog ID], count);
    }
    
    - (void) dealloc
    {
        self.dog = nil;
        [super dealloc];
    }
    
    @end

    Person.h

    View Code
    #import <Foundation/Foundation.h>
    #import "Dog.h"
    
    @interface Person : NSObject <DogBark>
    {
        Dog *_dog;
    }
    @property (retain) Dog *dog;
    
    @end
  • 相关阅读:
    解决ubuntu中firefox浏览器总是提示找不到server的问题
    Android学习笔记(14):相对布局RelativeLayout
    浅析java(多方面解读)
    做自己
    SGU 261. Discrete Roots (N次剩余)
    hdu1115 Lifting the Stone(几何,求多边形重心模板题)
    Android编码规范
    hdu 3790 最短路径问题
    怎样在gluster的源代码中加入自己的xlator
    处理空列表
  • 原文地址:https://www.cnblogs.com/caishuhua226/p/2833239.html
Copyright © 2020-2023  润新知