OC-观察者练习练习

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"]);
    
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值