KVO概念和用法

来源:互联网 发布:php urlsafeb64encode 编辑:程序博客网 时间:2024/06/06 00:50

参考:http://www.cnblogs.com/pengyingh/articles/2383629.html

          http://www.mamicode.com/info-detail-515516.html   

    源码电脑里有!

知识点介绍

一,概述

KVO的是KeyValue Observe的缩写,中文是键值观察。这是一个典型的观察者模式,观察者在键值改变时会得到通知。iOS中有个Notification的机制,也可以获得通知,但这个机制需要有个Center,相比之下KVO更加简洁而直接。

二,使用方法

系统框架已经支持KVO,所以程序员在使用的时候非常简单。

1. 注册,指定被观察者的属性,

2. 实现回调方法

3. 移除观察

四,小结

KVO这种编码方式使用起来很简单,很适用与datamodel修改后,引发的UIVIew的变化这种情况

KVO的优点:

当 有属性改变,KVO会提供自动的消息通知。这样的架构有很多好处。首先,开发人员不需要自己去实现这样的方案:每次属性改变了就发送消息通知。这是KVO 机制提供的最大的优点。因为这个方案已经被明确定义,获得框架级支持,可以方便地采用。开发人员不需要添加任何代码,不需要设计自己的观察者模型,直接可 以在工程里使用。其次,KVO的架构非常的强大,可以很容易的支持多个观察者观察同一个属性,以及相关的值。

      KVO的使用也很简单,就是简单的3步。
      1.注册需要观察的对象的属性addObserver:forKeyPath:options:context:
      2.实现observeValueForKeyPath:ofObject:change:context:方法,这个方法当观察的属性变化时会自动调用
      3.取消注册观察removeObserver:forKeyPath:context:

Demo:

  1. @interface myPerson : NSObject  
  2. {  
  3.     NSString *_name;  
  4.     int      _age;  
  5.     int      _height;  
  6.     int      _weight;  
  7. }  
  8. @end  
  9.   
  10. @interface testViewController : UIViewController  
  11. @property (nonatomic, retain) myPerson *testPerson;  
  12.   
  13. - (IBAction)onBtnTest:(id)sender;  
  14. @end  
  15.   
  16. - (void)testKVO  
  17. {  
  18.     testPerson = [[myPerson alloc] init];  
  19.       
  20.     [testPerson addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew context:nil];  
  21. }  
  22.   
  23. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context  
  24. {  
  25.     if ([keyPath isEqualToString:@"height"]) {  
  26.         NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]);  
  27.     } else {  
  28.         [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];  
  29.     }  
  30. }  
  31.   
  32. - (IBAction)onBtnTest:(id)sender {  
  33.     int h = [[testPerson valueForKey:@"height"] intValue];      
  34.     [testPerson setValue:[NSNumber numberWithInt:h+1] forKey:@"height"];  
  35.     NSLog(@"person height=%@", [testPerson valueForKey:@"height"]);  
  36. }  
  37.   
  38. - (void)dealloc  
  39. {  
  40.     [testPerson removeObserver:self forKeyPath:@"height" context:nil];  
  41.     [super dealloc];  
  42. }  

第一段代码声明了myPerson类,里面有个_height的属性。在testViewController有一个testPerson的对象指针。
      在testKVO这个方法里面,我们注册了testPerson这个对象height属性的观察,这样当testPerson的height属性变化时, 会得到通知。在这个方法中还通过NSKeyValueObservingOptionNew这个参数要求把新值在dictionary中传递过来。
      重写了observeValueForKeyPath:ofObject:change:context:方法,这个方法里的change这个NSDictionary对象包含了相应的值。
      需要强调的是KVO的回调要被调用,属性必须是通过KVC的方法来修改的,如果是调用类的其他方法来修改属性,这个观察者是不会得到通知的。



0 0
原创粉丝点击