iOS--KVO的概述与使用
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
程序解析如下:
//StockData.h
#import <Foundation/Foundation.h> @interface StockData : NSObject
{
NSString * stockName;
float price;
}
@end
//StockData.m
#import "StockData.h"
@implementation StockData @end
- (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"]];
}
}
*/
/**
* 移除观察者
*/
-(void)dealloc
{
[self.stockforKVO removeObserver:self forKeyPath:@"price"];
}

iOS--KVO的概述与使用的更多相关文章
- iOS KVO概述
iOS KVO概述 面试中经常会被问到:什么是KVO?这个问题既然出现概率这么大,那么我们就来详细讲一讲到底什么是KVO.下次再有面试官问你的时候,你就可以娓娓道来,以彰显高逼格 概述 问:什么是KV ...
- iOS:KVO/KVC 的概述与使用
iOS:KVO/KVC 的概述与使用 KVO APP开发技术QQ群:347072638 一,概述 KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性 ...
- iOS Foundation 框架概述文档:常量、数据类型、框架、函数、公布声明
iOS Foundation 框架概述文档:常量.数据类型.框架.函数.公布声明 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业 ...
- iOS kvo 结合 FBKVOController 的使用
iOS kvo 结合 FBKVOController 的使用 一:FBKVOControlloer是FaceBook开源的一个 在 iOS,maxOS上使用 kvo的 开源库: 提供了block和@s ...
- kvo原理概述
kvo概述 kvo,全称Key-Value Observing,它提供了一种方法,当对象某个属性发生改变时,允许监听该属性值变化的对象可以接受到通知,然后通过kvo的方法响应一些操作. kvo实现原理 ...
- KVO的概述的使用
一,概述 KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知.简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应 ...
- iOS KVO & KVC
键值观察:值更改时通知观察者 键值观察(Key-value observing,或简称 KVO)允许对象观察另一个对象的属性.该属性值改变时,会通知观察对象.它了解新值以及旧值:如果观察的属性为对多的 ...
- KVO的概述与使用
一,概述 KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知.简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知 ...
- iOS KVO详解
一.KVO 是什么? KVO 是 Objective-C 对观察者设计模式的一种实现.[另外一种是:通知机制(notification),详情参考:iOS 趣谈设计模式——通知]: KVO 提供一种机 ...
- iOS设计模式 - (1)概述
近期可自由安排的时间比較多, iOS应用方面, 没什么好点子, 就先放下, 不写了.花点时间学学设计模式. 之后将会写一系列博文, 记录设计模式学习过程. 当然, 由于我自己是搞iOS的, 所以之后设 ...
随机推荐
- 重置EntityFramework数据迁移到洁净状态
前言 翻译一篇有关EF数据迁移的文章,以备日后所用,文章若有翻译不当的地方请指出,将就点看,废话少说,看话题.[注意]:文章非一字一句的翻译,就重要的问题进行解释并解决. 话题引入 无法确定这种场景是 ...
- 追根溯源:EntityFramework 实体的状态变化
阅读目录: 1. 应用场景 2. 场景测试 3. 问题分析 4. 追根溯源 5. 简要总结 1. 应用场景 首先,应用程序使用 EntityFramework,应用场景中有两个实体 S_Class(班 ...
- EntityFramework 如何进行异步化(关键词:async·await·SaveChangesAsync·ToListAsync)
应用程序为什么要异步化?关于这个原因就不多说了,至于现有项目中代码异步化改进,可以参考:实际案例:在现有代码中通过async/await实现并行 这篇博文内容针对的是,EntityFramework ...
- 机器学习基础——梯度下降法(Gradient Descent)
机器学习基础--梯度下降法(Gradient Descent) 看了coursea的机器学习课,知道了梯度下降法.一开始只是对其做了下简单的了解.随着内容的深入,发现梯度下降法在很多算法中都用的到,除 ...
- Oracle 10g安全加固(审计、监听密码)
环境: Linux 6.4 + Oracle 10.2.0.4 1. Oracle 10g 审计功能 2. 对数据库监听器的关闭和启动设置密码 1. Oracle 10g 审计功能 Oracle 10 ...
- 移动端用js与jquery实时监听输入框值的改动
背景: 在一次移动端H5开发中,需要监听输入框值的实时变动. onchange事件肯定抛弃,因为只能失去焦点才触发. 而keyPress在Android可以触发,iOS不可以. 又不想用Android ...
- java.util.ConcurrentModificationException异常处理
ConcurrentModificationException异常处理 ConcurrentModificationException异常是Iterator遍历ArrayList或者HashMap数组 ...
- 数据库join方式分析
前言 不管是博客园还是CSDN,看到很多朋友对数据库的理解.认识还是没有突破一个瓶颈 ,而这个瓶颈往往只是一层窗纸,越过了你将看到一个新世界. 04.05年做项目的时候,用SQL Serv ...
- 【原创】技术往事:改变世界的TCP/IP协议(珍贵多图、手机慎点)
1.前言 作为应用层开发人员,接触最多的网络协议通常都是传输层的TCP(与之同处一层的另一个重要协议是UDP协议),但对于IP协议,对于应用程序员来说更多的印象还是IP地址这个东西,再往深一点也就很难 ...
- 初入网络系列笔记(1)TCP/IP基础
一.借鉴说明,本博文借鉴以下博文 1.BlueTzar,TCP/IP四层模型, http://www.cnblogs.com/BlueTzar/articles/811160.html 2.叶剑峰,漫 ...