KVO设计模式(监听对象属性的变化)
#import "ViewController.h"
#import "BOSS.h"
#warning 事件监听的唯一标志 要保证这个id的唯一话,后面的字符串不能重复
void * identifier = &"BossDistance";
@interface ViewController ()
{
BOSS *wang;
NSTimer *_timer;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//你在办公室上班 玩游戏
//请同事盯着老板,当老板位置发生变化的时候,及时通知
//BOSS
//KVO 是key - Value - Observing
//键值监听,我们可以监听某一个模型的某一个key 当这个key 的值发生变化的时候,我们能够实时的获取这种变化
//KVO 创建思路
//1.需要对某一个对象的某个属性进行监听
//2.实现属性发生变化后的回调 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//3.属性一定不要通过下划线进行变化
// 4.不需要监听的时候,一定要移除监听
// 5. 被监听的对象释放前,一定要移除监听
//实例化一个老板
wang = [[BOSS alloc] init];
// 监听BOSS 的distance属性
//给某一个对象(王)添加一个事件监听
//Observer:监听者 是谁再监听那个(wang)对象
//keyPath: 监听哪一个属性的变化
/*
NSKeyValueObservingOptionNew 0x01,// 变化后的距离
NSKeyValueObservingOptionOld = 0x02, // 变化前距离
NSKeyValueObservingOptionInitial // 最初的
NSKeyValueObservingOptionPrior // 再某事以前的
*/
[ wang addObserver:self forKeyPath:@"distance" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:identifier];
//让老板动起来
// [wang walk];
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:wang selector:@selector(walk) userInfo:nil repeats:YES];
}
// KVO 监听的对象属性发生变化的时候,会调用这个方法
//keyPath:表示的是,发生变化的属性
//object:被监听的对象
//change:字典里面存有变化前后的值
//context: 是事件监听的唯一标志
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == identifier) {
//拿到变化前的值
float oldValue = [change[NSKeyValueChangeOldKey] floatValue];
//拿到变化后的值
float newValue = [change [NSKeyValueChangeNewKey] floatValue];
NSLog(@"%g ---> %g",oldValue,newValue);//%g 舍去小数点后多余的0 保留有效数字就可以
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)dealloc{
//移除监听
[wang removeObserver:self forKeyPath:@"distance" context:identifier];
if (_timer) {
[_timer invalidate];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[_timer setFireDate:[NSDate distantFuture]];
}
@end
BOSS类
#import <Foundation/Foundation.h>
@interface BOSS : NSObject
//Boss 和你的距离
@property (nonatomic,assign)float distance;
- (void)walk;
@end
#import "BOSS.h"
@implementation BOSS
- (void)walk{
//在这里,对老板的distance属性进行赋值
//随机的距离
float distance = arc4random() % 100 + 1;// 1 - 100
//下面的两种方式可以被KVO监听到
// self.distance = distance;
[self setValue:@(distance) forKey:@"distance"];
//以这种方式放生的变化,不会被KVO监听到
// _distance = distance;
}
@end
KVO设计模式(监听对象属性的变化).png
网友评论