zoukankan      html  css  js  c++  java
  • 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"]];
        }
    }
  • 相关阅读:
    nginx教程2:日志
    3.1.1 基于监听的事件处理机制
    示例(1)按键和文本框监听
    2.3.3 Button(按钮)与ImageButton(图像按钮)
    2.3.2 EditText(输入框)详解
    2.3.1 TextView(文本框)详解
    2.2.3 TableLayout(表格布局)
    2.2.2 RelativeLayout(相对布局)
    2.2.1 LinearLayout(线性布局)
    2.1 View与ViewGroup的概念
  • 原文地址:https://www.cnblogs.com/niit-soft-518/p/6245531.html
Copyright © 2011-2022 走看看