KVO机制

KVO,全称为Key-Value Observing,是iOS中的一种设计模式,用来监测对象的某些属性的实时变化情况并作出响应

 

首先,假设我们的目标是在一个UITableViewController内对tableview的contentOffset进行实时监测,很容易地使用KVO来实现为。

[_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];



在dealloc中移除KVO监听:

[_tableView removeObserver:self forKeyPath:@"contentOffset" context:nil];



//判断改变的属性,监测的属性改变时 触发此方法
 (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context
{
    if (object == _tableView && [keyPath isEqualToString:@"contentOffset"]) {
[self doSomethingWhenContentOffsetChanges];

} }

 

也可以监测字典类型的key属性。

 


dict=[[NSMutableDictionary alloc]initWithDictionary:@{@"value":@"start"}];
    [self.lb_title setText:[dict objectForKey:@"value"]];
    [dict addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"value"]) {
        [self.lb_title setText:[change objectForKey:@"new"]];
    }
}

 

posted @ 2017-01-03 16:58  爱生活爱代码  阅读(229)  评论(0)    收藏  举报