OC KVO应用简介


一、OC KVO简介

KVO:Key Value Observing
KVO 是观察者模式的一种应用,主要用于监控属性(property)的变化,KVO同NSNotification有很多相似的地方。
KVO 用法:

addObserver:添加监控的属性
removerObserver:移出监控
observerValueForKeyPath:回调方法


二、OC KVO应用

//testClass.h
#import "Foundation / Foundation.h"
@interface testClass : NSObject
{
    NSString *info1;
    double   *info2;
}
@end
//testClass.m
#import "testClass.h"
@implementation testClass
@end

//  ViewController.h
#import "UIKit / UIKit.h"
#import "testClass.h"
@interface ViewController : UIViewController{
    testClass *t;
    UILabel *label;
}
@end

//ViewController.m 
#import "ViewController.h"
@interface ViewController ()
@end

@implementation ViewController
-(void)dealloc{
    //[super dealloc];
    [t removeObserver:self forKeyPath:@"info1"];
    //[t release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    t =[[testClass alloc]init]; //初始化实体

    //设置属性
    [t setValue:@"测试信息678" forKey:@"info1"];
    //添加监听
    [t addObserver:self forKeyPath:@"info1" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    
    //设置一个UILabel 显示info1
    label = [[UILabel alloc]initWithFrame:CGRectMake(100,100,100,50)];
    label.textColor  = [UIColor redColor];
    label.text = [t valueForKey:@"info1"];
    [self.view addSubview:label];
    
    //添加一个按钮,并通过按钮点击事件改变属性值
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(300,100,60,20);
    [btn setTitle:@"回调" forState:UIControlStateNormal]; //设置按钮上文字
    btn.backgroundColor = [UIColor redColor]; //设置按钮背景色
    [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside]; //设置按钮事件
    [self.view addSubview: btn];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//监控
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
   if([keyPath isEqualToString:@"info1"])
   {
       NSLog(@"回调");
       label.text  = [t valueForKey:@"info1"];
   }
}

//按钮事件
-(void)btnAction{
   [t setValue:@"890" forKey:@"info1"];
}

@end


三、OC KVO应用场景

KVO主要应用实体数据展示,当一个实体数据变化,我们可以通过KVO模式,修改view上的数据

相关阅读:
KVC 简介