Objective-C学习之旅(八)----代理设计模式

一、协议的具体用法

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

二、如何实现代理

  这里介绍一个案例

《Objective-C学习之旅(八)----代理设计模式》

三、代理两端如何通讯

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

四、调用前后顺序的问题

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

五、demo

dog.m

《Objective-C学习之旅(八)----代理设计模式》
《Objective-C学习之旅(八)----代理设计模式》
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

《Objective-C学习之旅(八)----代理设计模式》
《Objective-C学习之旅(八)----代理设计模式》
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

《Objective-C学习之旅(八)----代理设计模式》
《Objective-C学习之旅(八)----代理设计模式》
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

《Objective-C学习之旅(八)----代理设计模式》
《Objective-C学习之旅(八)----代理设计模式》
View Code

#import <Foundation/Foundation.h>
#import "Dog.h"

@interface Person : NSObject <DogBark>
{
    Dog *_dog;
}
@property (retain) Dog *dog;

@end

 

    原文作者:设计模式
    原文地址: http://www.cnblogs.com/caishuhua226/archive/2012/12/25/2833239.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞