[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);的方法,所以更灵活,但是变更属性时不能简单赋值!