OC循环渐进:KVO的使用

设计模式中有一种模式叫:观察者模式,在OC中我们就用KVO去实现观察者模式。


KVO是基于KVC的一种技术,当我们使用KVO去观察一个对象的属性后,使用KVC去改变这个属性的值时,就会通知观察者。
接下来我们讲一个KVO的实例:
1.建立一个英雄类Hero和Support类,Support类作为英雄类的血量属性的观察者,当英雄血量发生变化时,通知观察者Support类。
Hero.h 的文件代码如下:

#import <Foundation/Foundation.h>

@interface Hero : NSObject {
    NSInteger _HP;  //血量
}

@end

Hero.m 的文件代码如下:

#import "Hero.h"

@implementation Hero

@end

Support.h 的文件代码如下:

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

@interface Support : NSObject

@property (nonatomic,strong) Hero *hero;

- (id)initWithHero:(Hero *)hero;

@end

Support.m 的文件代码如下:

#import "Support.h"

@implementation Support


- (id)initWithHero:(Hero *)hero {

//可以对类中的某个【对象】属性添加观察者。。。。。
    if (self = [super init]) {
        self.hero = hero;
        [self.hero addObserver:self forKeyPath:@"_HP"
        options:NSKeyValueObservingOptionNew context:nil];//添加观察者
    }
    return self;

}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
        change:(NSDictionary *)change context:(void *)context {

//定义回调
    if ([keyPath isEqualToString:@"_HP"]) {
        NSLog(@"change = %@",change);
        NSInteger curHp = [change[@"new"] integerValue];
        if (curHp <= 5 && curHp > 0) {
            NSLog(@"你快死了");
        }
        if (curHp == 0) {
            NSLog(@"你死了,Game over!!!");
        }
    }

}


- (void)dealloc {

//移除观察者
    [self.hero removeObserver:self forKeyPath:@"_HP" context:nil];
}


- (void)reduce:(NSTimer *)timer {

//定时器调用方法,每次英雄血量-5NSInteger curHp = [[self valueForKeyPath:@"_hero._HP"] integerValue];
    curHp -= 5;
    if (curHp == 0) {
        [timer invalidate];
        timer = nil;
    }
        NSNumber *number = [NSNumber numberWithInteger:curHp];
        [self setValue:number forKeyPath:@"_hero._HP"];

}

@end

main.m 的文件代码如下:

#import <Foundation/Foundation.h>
#import "Support.h"
#import "Hero.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Hero *hero = [[Hero alloc] init];
        [hero setValue:@15 forKey:@"_HP"];
        Support *support = [[Support alloc] initWithHero:hero];

        [NSTimer scheduledTimerWithTimeInterval:1.0 target:support selector:@selector(reduce:) userInfo:nil repeats:YES];

        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

测试结果如下:

2015-08-08 14:32:54.543 Demo01[867:62213] change = {
    kind = 1;
    new = 10;
}
2015-08-08 14:32:55.542 Demo01[867:62213] change = {
    kind = 1;
    new = 5;
}
2015-08-08 14:32:55.545 Demo01[867:62213] 你快死了
2015-08-08 14:32:56.543 Demo01[867:62213] change = {
    kind = 1;
    new = 0;
}
2015-08-08 14:32:56.543 Demo01[867:62213] 你死了,Game over!!!

以上就是KVO观察者模式的内容!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值