iOS知识点总结——KVO

参考文章:http://blog.csdn.net/yuquan0821/article/details/6646400


一,概述

KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

二,使用方法

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

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

2. 实现回调方法

3. 移除观察

三,实例:

假设一个场景,股票的价格显示在当前屏幕上,当股票价格更改的时候,实时显示更新其价格。

1.定义DataModel,

[cpp]  view plain copy
  1. @interface StockData : NSObject {  
  2.     NSString * stockName;  
  3.     float price;  
  4. }  
  5. @end  
  6. @implementation StockData  
  7. @end  


2.定义此model为Controller的属性,实例化它,监听它的属性,并显示在当前的View里边

[cpp]  view plain copy
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.   
  5.     stockForKVO = [[StockData alloc] init];  
  6.     [stockForKVO setValue:@"searph" forKey:@"stockName"];  
  7.     [stockForKVO setValue:@"10.0" forKey:@"price"];      
  8.     [stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];  
  9.   
  10.     myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];  
  11.     myLabel.textColor = [UIColor redColor];  
  12.     myLabel.text = [stockForKVO valueForKey:@"price"];  
  13.     [self.view addSubview:myLabel];  
  14.      
  15.     UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  16.     b.frame = CGRectMake(0, 0, 100, 30);  
  17.     [b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];  
  18.     [self.view addSubview:b];  
  19.   
  20. }  


3.当点击button的时候,调用buttonAction方法,修改对象的属性

[cpp]  view plain copy
  1. -(void) buttonAction  
  2. {  
  3.     [stockForKVO setValue:@"20.0" forKey:@"price"];  
  4. }  

4. 实现回调方法

[cpp]  view plain copy
  1. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context  
  2. {  
  3.     if([keyPath isEqualToString:@"price"])  
  4.     {  
  5.         myLabel.text = [stockForKVO valueForKey:@"price"];  
  6.     }  
  7. }  

5.增加观察与取消观察是成对出现的,所以需要在最后的时候,移除观察者

[cpp]  view plain copy
  1. - (void)dealloc  
  2. {  
  3.     [super dealloc];  
  4.     [stockForKVO removeObserver:self forKeyPath:@"price"];  
  5.     [stockForKVO release];  
  6. }  

四,小结

KVO这种编码方式使用起来很简单,很适用与datamodel修改后,引发的UIVIew的变化这种情况,就像上边的例子那样,当更改属性的值后,监听对象会立即得到通知。

   KVO在程序中使用的非常之多,其本质就是观察者模式,在很多时候与NSNotification和Delegate可以通用,下面是另外一个网页上的Demo,本人已经按照demo实践过,非常好用:(http://blog.csdn.net/chen505358119/article/details/9354571)

 最近研究了一下子KVC和KVO,KVC:即Key-Value-Coding 而KVO:即Key-Value-Observer

      KVC是针对NSObject的子类,因为它的实现是由于其括展类NSObject(NSKeyValueCoding),实现了

   - (void)setValue:(id)value forKey:(NSString *)key;   

    - (id)valueForKey:(NSString *)key;这两个方法的原因。

  还有一个说清楚点就是上面的两个方法不光针对属性,对于类中的对象型变量同样适用。

  而KVO也差不多,它是由于NSObject(NSKeyValueObserverRegistration)和NSObject(NSKeyValueObserving)的原因,用它可以实现回调功能下面是我写的,下面的例子我将其融合在一起

  

  

[plain]  view plain copy print ?
  1. #import "BIDViewController.h"  
  2. #import "FirstViewController.h"  
  3. @interface BIDViewController ()  
  4. {  
  5.     FirstViewController* first;  
  6.       
  7. }  
  8. @end  
  9.   
  10. @implementation BIDViewController  
  11.   
  12. - (void)viewDidLoad  
  13. {  
  14.     [super viewDidLoad];  
  15.     // Do any additional setup after loading the view, typically from a nib.  
  16.     first=[[FirstViewController alloc] init];  
  17.     //观察FirstViewController中的变量name  
  18.     [first addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];  
  19. }  
  20.   
  21. - (void)didReceiveMemoryWarning  
  22. {  
  23.     [super didReceiveMemoryWarning];  
  24.     // Dispose of any resources that can be recreated.  
  25. }  
  26.   
  27. - (IBAction)clicked:(UIButton *)sender {  
  28.     [self presentViewController:first animated:YES completion:^{}];  
  29. }  
  30. //如果FirstViewController中的变量name的值变化执行下面  
  31. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context  
  32. {  
  33.     if([keyPath isEqualToString:@"name"])  
  34.     {  
  35.         NSLog(@"observer name is %@",[first valueForKey:@"name"]);  
  36.     }  
  37. }  
  38.   
  39. -(void)dealloc  
  40. {  
  41.     [self removeObserver:first forKeyPath:@"name"];  
  42.     [first release];  
  43.     [super dealloc];  
  44. }  
  45. @end  

[plain]  view plain copy print ?
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface FirstViewController : UIViewController  
  4. {  
  5.     NSString* name;  
  6. }  
  7. - (IBAction)clicked:(id)sender;  
  8. - (IBAction)otherClicked:(id)sender;  
  9.   
  10. @end  


[plain]  view plain copy print ?
  1. #import "FirstViewController.h"  
  2.   
  3. @interface FirstViewController ()  
  4. {  
  5. }  
  6. @end  
  7.   
  8. @implementation FirstViewController  
  9. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  10. {  
  11.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  12.     if (self) {  
  13.         // Custom initialization  
  14.     }  
  15.     return self;  
  16. }  
  17.   
  18. - (void)viewDidLoad  
  19. {  
  20.     [super viewDidLoad];  
  21.     // Do any additional setup after loading the view from its nib.  
  22. }  
  23.   
  24. - (void)didReceiveMemoryWarning  
  25. {  
  26.     [super didReceiveMemoryWarning];  
  27.     // Dispose of any resources that can be recreated.  
  28. }  
  29.   
  30. - (IBAction)clicked:(id)sender {  
  31.     //当为name设值时会执行BIDViewController中的观察方法,就可进行回调了,不过其范围是比不上真正意义上的回调  
  32.     [self setValue:@"chenliang" forKey:@"name"];  
  33.   
  34. //    [self dismissModalViewControllerAnimated:YES];  
  35.       
  36.       
  37. }  
  38.   
  39. - (IBAction)otherClicked:(id)sender {  
  40.       
  41.     NSLog(@"firstVC name is %@",[self valueForKey:@"name"]);  
  42. }  
  43. @end  




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值