一、概述

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

 
二、使用方法

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

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

2. 实现回调方法

3. 移除观察

 
三、实例:
  假设一个场景,股票的价格显示在当前屏幕上,当股票价格更改的时候,实时显示更新其价格。
程序目录如下:
 

工程程序如下:

StockData.h


#import <Foundation/Foundation.h>

@interface StockData : NSObject
{
NSString * stockName;
float price;
}
@end

StockData.m


#import "StockData.h"
@implementation StockData @end

这里定义属性是在ViewController.m文件里定义的,而ViewController.h里没有内容,故而没有列举出来。

ViewController.m


#import "ViewController.h"
#import "StockData.h"
@interface ViewController () @property(strong,nonatomic) UILabel *myLable;
@property(strong,nonatomic) StockData *stockforKVO; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
self.stockforKVO=[[StockData alloc] init];
[self.stockforKVO setValue:@"searph" forKey:@"stockName"];
[self.stockforKVO setValue:@"10.0" forKey:@"price"];
[self.stockforKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
self.myLable = [[UILabel alloc]initWithFrame:CGRectMake(, , , )];
self.myLable.textColor = [UIColor redColor];
self.myLable.text = [NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];
[self.view addSubview:self.myLable]; UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(, , , );
b.backgroundColor=[UIColor redColor];
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}
-(void)buttonAction
{
// 点击按钮 切换数值
[self.stockforKVO setValue:[NSString stringWithFormat:@"%d",arc4random()%] forKey:@"price"];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ if ([keyPath isEqualToString:@"price"]) {
self.myLable.text= [NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];
NSLog(@"旧数据--%@--,新数据--%@--",[change objectForKey:@"old"],[change objectForKey:@"new"]);
} } /*
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"])
{
self.myLable.text=[NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];
}
}
*/ /**
* 移除观察者
*/
-(void)dealloc
{
[self.stockforKVO removeObserver:self forKeyPath:@"price"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

程序解析如下:

1.定义DataModel,即自己定义的类

//StockData.h
#import <Foundation/Foundation.h> @interface StockData : NSObject
{
NSString * stockName;
float price;
}
@end

//StockData.m
#import "StockData.h"
@implementation StockData

@end
 
2.定义此model为Controller的属性,实例化它,监听它的属性,并显示在当前的View里边
- (void)viewDidLoad {
[super viewDidLoad];
self.stockforKVO=[[StockData alloc] init];
[self.stockforKVO setValue:@"searph" forKey:@"stockName"];
[self.stockforKVO setValue:@"10.0" forKey:@"price"];
[self.stockforKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
self.myLable = [[UILabel alloc]initWithFrame:CGRectMake(, , , )];
self.myLable.textColor = [UIColor redColor];
self.myLable.text = [NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];
[self.view addSubview:self.myLable]; UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(, , , );
b.backgroundColor=[UIColor redColor];
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}

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

-(void)buttonAction
{
// 点击按钮 切换数值
[self.stockforKVO setValue:[NSString stringWithFormat:@"%d",arc4random()%] forKey:@"price"];
}

4. 实现回调方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    if ([keyPath isEqualToString:@"price"]) {
self.myLable.text= [NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];
NSLog(@"旧数据--%@--,新数据--%@--",[change objectForKey:@"old"],[change objectForKey:@"new"]);
} } /*
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"])
{
self.myLable.text=[NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];
}
}
*/
5.增加观察与取消观察是成对出现的,所以需要在最后的时候,移除观察者
/**
* 移除观察者
*/
-(void)dealloc
{
[self.stockforKVO removeObserver:self forKeyPath:@"price"];
}
四、小结
 
KVO这种编码方式使用起来很简单,很适用与datamodel修改后,引发的UIVIew的变化这种情况,就像上边的例子那样,当更改属性的值后,监听对象会立即得到通知。
 
五、程序效果图

iOS--KVO的概述与使用的更多相关文章

  1. iOS KVO概述

    iOS KVO概述 面试中经常会被问到:什么是KVO?这个问题既然出现概率这么大,那么我们就来详细讲一讲到底什么是KVO.下次再有面试官问你的时候,你就可以娓娓道来,以彰显高逼格 概述 问:什么是KV ...

  2. iOS:KVO/KVC 的概述与使用

    iOS:KVO/KVC 的概述与使用       KVO   APP开发技术QQ群:347072638 一,概述 KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性 ...

  3. iOS Foundation 框架概述文档:常量、数据类型、框架、函数、公布声明

    iOS Foundation 框架概述文档:常量.数据类型.框架.函数.公布声明 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业 ...

  4. iOS kvo 结合 FBKVOController 的使用

    iOS kvo 结合 FBKVOController 的使用 一:FBKVOControlloer是FaceBook开源的一个 在 iOS,maxOS上使用 kvo的 开源库: 提供了block和@s ...

  5. kvo原理概述

    kvo概述 kvo,全称Key-Value Observing,它提供了一种方法,当对象某个属性发生改变时,允许监听该属性值变化的对象可以接受到通知,然后通过kvo的方法响应一些操作. kvo实现原理 ...

  6. KVO的概述的使用

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

  7. iOS KVO & KVC

    键值观察:值更改时通知观察者 键值观察(Key-value observing,或简称 KVO)允许对象观察另一个对象的属性.该属性值改变时,会通知观察对象.它了解新值以及旧值:如果观察的属性为对多的 ...

  8. KVO的概述与使用

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

  9. iOS KVO详解

    一.KVO 是什么? KVO 是 Objective-C 对观察者设计模式的一种实现.[另外一种是:通知机制(notification),详情参考:iOS 趣谈设计模式——通知]: KVO 提供一种机 ...

  10. iOS设计模式 - (1)概述

    近期可自由安排的时间比較多, iOS应用方面, 没什么好点子, 就先放下, 不写了.花点时间学学设计模式. 之后将会写一系列博文, 记录设计模式学习过程. 当然, 由于我自己是搞iOS的, 所以之后设 ...

随机推荐

  1. Android自定义spinner下拉框实现的实现

    一:前言 本人参考博客:http://blog.csdn.net/jdsjlzx/article/details/41316417 最近在弄一个下拉框,发现Android自带的很难实现我的功能,于是去 ...

  2. scikit-learn K近邻法类库使用小结

    在K近邻法(KNN)原理小结这篇文章,我们讨论了KNN的原理和优缺点,这里我们就从实践出发,对scikit-learn 中KNN相关的类库使用做一个小结.主要关注于类库调参时的一个经验总结. 1. s ...

  3. 安装nginx

    [yum安装nginx] yum clean all(这步不执行会出现no more mirrors to try错误) cd /etc/yum.repos.d/ vi nginx.repo 填写 [ ...

  4. Oracle内存管理技术

    1.Oracle内存管理技术 2.配置自动内存管理(AMM) 3.监视自动内存管理(AMM) 4.配置自动共享内存管理(ASMM) 5.配置自动PGA内存管理 Reference 1.Oracle内存 ...

  5. struts2学习笔记--使用Validator校验数据

    我们在进行一些操作是需要对用户的输入数据进行验证,比如网站的注册,需要对各个数据项进行数据校验,Struts2提供了一些默认的校验器,比如数字的检测,邮箱的检测,字符串长度的检测等等. 常用的Vali ...

  6. android获得ImageView图片的等级

    android获得ImageView图片的等级问题 要实现的功能如下图,点击分享能显示选中与不选中状态,然后发送是根据状态来实现具体分享功能. 在gridview中有5个子项,每个子元素都有两张图片A ...

  7. JDBC连接SQL Server代码模板

    *                  JDBC连接SQL Server数据库 代码模板* Connection: 连接数据库并担任传送数据的任务:* Statement :  执行SQL语句:* Re ...

  8. 放养的小爬虫--豆瓣电影入门级爬虫(mongodb使用教程~)

    放养的小爬虫--豆瓣电影入门级爬虫(mongodb使用教程~) 笔者声明:只用于学习交流,不用于其他途径.源代码已上传github.githu地址:https://github.com/Erma-Wa ...

  9. MVC学习系列7--下拉框的联动

    [使用场景:两个DropDownList的联动,选择其中一个DropDownList,然后加载数据到另外的一个DropDownList上] 这里,我打算实现的需求是:有两个DropDownList,一 ...

  10. The SQL Server Service Broker for the current database is not enabled

    把一个数据恢复至另一个服务器上,出现了一个异常: The SQL Server Service Broker for the current database is not enabled, and ...