main.h
//被观察的对象
Jones *joens = [[Jones alloc] initWithJones];
//观察的对象
Lucy *lucy = [[Lucy alloc] initWithLucy:joens];
[[NSRunLoop currentRunLoop] run];
@interface Jones : NSObject
@property(nonatomic,assign) int happy;
-(instancetype)initWithJones;
//高兴值增加
-(void)happyIncrement;
————————————————————————————————
@implementation Jones
//高兴值
-(void)happyIncrement
{
//通过KVC才能触发KVO
NSNumber *number = [NSNumber numberWithInt:++_happy];
//[self setHappy:++_happy];
[self setValue:number forKey:@"happy"];
//[self setHappy:12]
NSLog(@"%d",self->_happy);
};
-(instancetype)initWithJones
{
if(self = [super init])
{
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(happyIncrement) userInfo:nil repeats:YES];
}
return self;
}
@implementation Jones
//高兴值
-(void)happyIncrement
{
//通过KVC才能触发KVO
NSNumber *number = [NSNumber numberWithInt:++_happy];
//[self setHappy:++_happy];
[self setValue:number forKey:@"happy"];
//[self setHappy:12]
NSLog(@"%d",self->_happy);
};
-(instancetype)initWithJones
{
if(self = [super init])
{
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(happyIncrement) userInfo:nil repeats:YES];
}
return self;
}
@implementation Lucy
-(instancetype)initWithLucy:(Jones *)jones
{
if (self = [super init])
{
//当Jones传入进来 我们就对他观察
self->_jones = jones;
self->_jones.happy = 0;
//添加观察者模式
/*
参数介绍 1,观察那个对象 2,观察那个属性 3,新值,和旧值 4,可以随便给
*/
[_jones addObserver:self forKeyPath:@"happy" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
};
return self;
}
//如果被观察者的对象属性被改变这个对象就回被触发!
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
/**
1.参数介绍
1.keyPath 那个属性
2.object 那个对象
3.change 属性大全
**/
//如果被监听属性加到10了 移除被观察的对象
if ([[change objectForKey:@"new"] intValue] == 10)
{
//移除观察者对象
[_jones removeObserver:self forKeyPath:@"happy"];
}
//否则打赢属性
NSLog(@"观察者调用了->%@",[change objectForKey:@"new"]);
};
OC-观察者练习练习
最新推荐文章于 2022-05-01 19:30:00 发布