• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、协议的具体用法

  协议的具体用法就是使用代理。代理设计模式相当于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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
为什么很多大公司继续使用Objective-C,不用Swift发布时间:2022-07-12
下一篇:
Objective-C自定义UISlider滑杆分段样式发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap