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-觀察者練習練習
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.