[IOS学习笔记]KVO

//属性
@property(nonatomic) BOOL isFinished;
//注册监听 [self addObserver:self forKeyPath:@"isFinished" options:0 context:NULL];
//响应变更事件 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"isFinished"]) { NSLog(@"changeeddd"); } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } }
//变更属性数值 [button addTarget:self action:@selector(changeFinished:) forControlEvents:UIControlEventTouchUpInside]; -(void)changeFinished:(id)sender { //自动通知 [self setValue:[NSNumber numberWithBool:YES] forKey:@"isFinished"]; }

注册监听器参数 options

NSKeyValueObservingOptionNew 表示属性未改变​之前的值;

NSKeyValueObservingOptionOld 表示属性改变后的值;​

 

移除观察者:

[subject removeObserver:observer forKeyPath:@"name"]; 

 

KVO相当于JAVA:

account.setListener(new MyListener(){

    inspector.method();

});

 

但是不需要和JAVA一样声明一个MyListener接口,也不需要在account类中新建一个setListeber(MyListener listener);的方法,所以更灵活,但是变更属性时不能简单赋值!

 

posted @ 2014-11-22 15:34  skyko  阅读(157)  评论(0编辑  收藏  举报