• KVO 简单使用


    http://www.verydemo.com/demo_c134_i5320.html
    1、什么是KVO?
    Key-Value-Observing(KVO,键值观察):当指定的对象的属性被修改了,允许对象接受到通知的机制。每次指定的被观察对象的属性被修改的时候,KVO都会自动的去通知相应的观察者。
    
    2、KVO有什么优点?
    当有属性改变,KVO会提供自动的消息通知。
    
    3、KVO实现
    1)注册观察者(Registering as an Observer),指定被观察的属性。
    addObserver:forKeyPath:options:context:
    2)接收变化通知(Receiving Notification of a Change),实现回调方法。
    observeValueForKeyPath:ofObject:change:context:
    3)移除观察者(Removing an Object as an Observer)
    removeObserver:forKeyPath:
    
    
    4、简单示例
    1)创建一个简单的SingleView模板的iPhone应用,我取名为KVODemo。
    2)在界面添加一个label和一个button,并生成相应的outlet。
    下面ViewConroller.h和ViewConroller.m
    
    ViewConroller.h源码清单:
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    @property (retain,nonatomic) IBOutlet UILabel *label;
    
    - (IBAction)buttonPressed:(UIButton *)sender;
    
    @end
    
    
    ViewConroller.m源码清单:
    
    #import "ViewController.h"
    @interface ViewController (){
        NSString *_str;
    }
    @property (nonatomic,retain) NSString *str;
    @end
    
    @implementation ViewController
    @synthesize label=_label;
    @synthesize str=_str;
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
        
        _str =@"sharon";    
        _label.text = _str;
        // 添加Observer  这样被注册的属性发生改变的时候Observer回调方法就被调用
        [selfaddObserver: selfforKeyPath: @"str"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    
    - (IBAction)buttonPressed:(UIButton *)sender {
       static BOOL flag =YES;
       if (flag) {
            // 修改正在监听的属性值  
            [selfsetValue: @"joe"forKey: @"str"];
        }else {
            // 修改正在监听的属性值  
            [selfsetValue: @"sharon"forKey: @"str"];
        }
        flag = !flag;    
    }
    
    // 实现Observer的回调方法
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {    
        // 如果改变的属性是"name"    
       if ([keyPath isEqualToString:@"str"]) {
            _label.text = [self valueForKey:@"str"];
            // 输出改变前的值
           NSLog(@"old str is %@",[changeobjectForKey:@"old"]);
            // 输出改变后的值
           NSLog(@"new str is %@",[changeobjectForKey:@"new"]); 
        }
    }
    
    -(void)dealloc{    
        // 移除Observer
        [selfremoveObserver:selfforKeyPath:@"name"];
        [super dealloc];
    }
    @end
    


  • 相关阅读:
    Design and Analysis of Algorithms_Decrease-and-Conquer
    TCPL 札记
    谬论:64 = 65?
    二叉树内部顶点与外部顶点在数量上的关系
    Design and Analysis of Algorithms_Divide-and-Conquer
    LeetCode 36. Valid Sudoku
    LeetCode 58. Length of Last Word
    LeetCode 66. Plus One
    LeetCode 67. Add Binary
    LeetCode 70. Climbing Stairs
  • 原文地址:https://www.cnblogs.com/zhangsongbai/p/3102588.html
Copyright © 2020-2023  润新知