delegate 使用

-----------------dog.h
#import <Foundation/Foundation.h>
@class Dog; //下面用到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 狗的主人 

  这一句 "  id <DogBark> delegate;"类似java里泛型声明一个接口"interface 接口"

  delegate的 类型是实现protocol DogBark 类型

}
@property int ID;
@property (assign) id <DogBark> delegate;
@end
-------------------------- dog.m
#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
----------------------------------------------person.h
#import <Foundation/Foundation.h>
#import "Dog.h"
@interface Person : NSObject <DogBark>
{
    Dog *_dog;
}
@property (retain) Dog *dog;
@end
-------------------------------------------------person.m
#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值