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


原文地址:https://www.cnblogs.com/zhangsongbai/p/3102588.html