一、概述

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. IDDD 实现领域驱动设计-架构之经典分层

    上一篇:<IDDD 实现领域驱动设计-上下文映射图及其相关概念> 在<实现领域驱动设计>书中,分层的概念作者讲述的很少,也就几页的内容,但对于我来说,有很多的感触需要诉说.之前 ...

  2. Hive创建表格报【Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException】引发的血案

    在成功启动Hive之后感慨这次终于没有出现Bug了,满怀信心地打了长长的创建表格的命令,结果现实再一次给了我一棒,报了以下的错误Error, return code 1 from org.apache ...

  3. ASP.NET实现微信功能(2)(服务号高级群发)

    前面写了一篇文章,关于微信的:http://www.cnblogs.com/kmsfan/p/4047097.html 今天打算来写本系列的第二批文章,服务号后台群发. 在写本篇文章之前,我们先来看看 ...

  4. Asp.Net 使用Npoi导出Excel

    引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...

  5. 7.1数据注解属性--Key【Code-First系列】

    Key特性可以被用到类的属性中,Code-First默认约定,创建一个主键,是以属性的名字“Id”,或者是类名+Id来的. Key特性重写了这个默认的约定,你可以应用Key特性到一个类的属性上面,不管 ...

  6. STM32L时钟

    Four different clock sources can be used to drive the system clock (SYSCLK): 1.HSI ((high-speed inte ...

  7. C#基础-out与ref字段

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...

  8. C#循环测试题

    关于如下程序结构的描述中,哪一项是正确的?   for ( ; ; ) { 循环体; //何问起   }   a) 不执行循环体b) 一直执行循环体,即死循环c) 执行循环体一次d) 程序不符合语法要 ...

  9. Sql数据库查询当前环境有无死锁

    DECLARE @spid INT , @bl INT , @intTransactionCountOnEntry INT , @intRowcount INT , @intCountProperti ...

  10. jQuery弹出深色系层菜单

    低调奢华jQuery弹出层菜单,使用新版的jQuery库,兼容多种浏览器.Demo展示: http://hovertree.com/texiao/layer/3/ 本特效可以作为网站的引导页,使用jQ ...