什么是KVC 什么是 KVO ?

KVC:(NSKey ValueCoding)”键-值  编码“是一种间接的访问对象属性(字符串表征)的机制。对象的属性都可以通过使用KVC机制用相同的方式访问。我们可以取而代之“设置器方法、点语法方法”去访问对象的属性。

KVO:(NSKey ValueObserving)"键-值 监听"是一种这样的机制,当对象的属性发生变化的时候,我们的监听者能够得到一个通知。

NSObject 类为所有的对象提供了一个自动检测能力的NSKey ValueObserving 协议。我们可以根据需要来打开这个监听机制。KVO是基于KVC而实现的。

KVC & KVO的使用

在使用KVC的时候,我们要注意,key 必须以小写字母开头,通常常和系统访问器方法同名。

获取属性:valueForKey:

设置属性:setValue: forKey:

KVC 对未定义的属性定义了 valueForUndefinedKey: 方法(重载方法获取定制的实现)

注意:KVC中的 value 都必须是对象。

基于KVC能够对对象的属性进行访问,当这个属性发生变化的时候,我们也能监听,这个监听的方法系统已经为我们实现了。我们所做的只需要去注册这个监听。注册之后就能很好的监听,属性的值变化了。下面就是KVO机制的注册和监听方法

1注册

-(void)addObserVer:(NSObject*)anObserver    forKeyPath:(NSString *)keyPath   options:(NSKeyValueObservingOptions)options   context:(void *)context

方法参数说明:keyPath 就是要观察的属性值,options 就是观察键值变化的选择 ,context 就是我们要传输的数据。其中options 是监听返回的字典所包含什么值。有两个常用的选项:NSKeyValueObservingOptionNew  返回的字典包含新值  NSKeyValueObservingOptionOld 指返回的字典包含旧值。

2.监听

-(void)obserValueForKeyPath:(NSString *)KeyPath   ofObject(id)object  change:(NSDictionary *)change  context:(void *)context

其中 change 里存储了一些变化的数据,比如变化前的数据,变化后的数据。

实例代码:

———————————————————————————————————————————————(.m文件)

#import "AppDelegate.h"
#import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
ViewController * vc = [[ViewController alloc]init];
self.window.rootViewController = vc;
return YES;
}

Appdelegate文件

———————————————————————————————————————————————(.h文件)

#import <Foundation/Foundation.h>

@interface Pweson : NSObject
@property(nonatomic,copy)NSString * name;
@property(nonatomic)NSInteger age; -(id)initWithDictionary:(NSDictionary *)dic;
@end ———————————————————————————————————————————————(.m文件) #import "Pweson.h" @implementation Pweson
-(id)initWithDictionary:(NSDictionary *)dic{
self = [super init];
if (self) {
[self setValuesForKeysWithDictionary:dic];
}
return self;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{ }
@end

person 文件

———————————————————————————————————————————————(.h文件)

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

———————————————————————————————————————————————(.m文件)

#import "ViewController.h"
#import "Pweson.h" @interface ViewController ()
@property(nonatomic,copy)Pweson * person;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
NSDictionary * dic = @{@"name":@"张华",@"age":@};
_person = [[Pweson alloc] initWithDictionary:dic];
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(, , , )];
label.textAlignment = NSTextAlignmentCenter;
label.text = _person.name;
[self.view addSubview:label];
[label release]; UILabel * agelabel = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
agelabel.tag = ;
agelabel.backgroundColor = [UIColor redColor];
agelabel.textAlignment = NSTextAlignmentCenter;
agelabel.text = [NSString stringWithFormat:@"%ld",self.person.age];
[self.view addSubview:agelabel];
[agelabel release]; UIButton * but = [UIButton buttonWithType:UIButtonTypeSystem];
but.frame = CGRectMake(, , , );
but.tintColor = [UIColor blueColor];
[but setTitle:@"增加1岁" forState:UIControlStateNormal];
[but addTarget:self action:@selector(addAge:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:but];
[but release]; }
-(void)addAge:(UIButton *)sender{
self.person.age += ;
} -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:@"age"]) {
((UILabel *)[self.view viewWithTag:]).text = [NSString stringWithFormat:@"%ld",self.person.age];
}
}

ViewController 文件

UI:KVO、KVC的更多相关文章

  1. iOS监听模式之KVO、KVC的高阶应用

    KVC, KVO作为一种魔法贯穿日常Cocoa开发,笔者原先是准备写一篇对其的全面总结,可网络上对其的表面介绍已经够多了,除去基本层面的使用,笔者跟大家谈下平常在网络上没有提及的KVC, KVO进阶知 ...

  2. UI:归档、反归档、数据持久化

    支持的文件读写类型:字符串.数组.字典.NSdata  (可变的.不可变的.共有8个类) 对于数组.字典在写入文件时,其中的元素也必须是以上四种类型之一. 支持的数据类型有限.且简单 写入文件: 字符 ...

  3. UI:多线程 、用GCD创建线程

    什么是应用(程序):就是我们编写的代码编译后生成的app文件 进程:凡是一个运行的程序都可以看作为一个进程,如打开的多个 word,就可以认为是一个进程的多个线程. 线程:至少有一个线程就是主线程,网 ...

  4. UI:UINavigationController、界面通信

    IOS中实现对控制器的管理的控制器有:UINavigationController 和 UITableBarController 两个控制器.下面是主要学习前者. 参考 ⼀.UINavigationC ...

  5. UI:UIScrollView、UIPageControl

    一.UIScrollView的常⽤用属性 二.UIScrollView的常⽤用代理方法 三.UIPageControl的使⽤用 四.UIPageControl与UIScrollView的结合使⽤用 U ...

  6. KVC、KVO、NSNotification、delegate 总结及区别

    1.KVC,即是指 NSKeyValueCoding,一个非正式的Protocol,提供一种机制来间接访问对象的属性.而不是通过调用Setter.Getter方法访问.KVO 就是基于 KVC 实现的 ...

  7. iOS 中KVC、KVO、NSNotification、delegate 总结及区别-b

    1.KVC,即是指 NSKeyValueCoding,一个非正式的Protocol,提供一种机制来间接访问对象的属性.而不是通过调用Setter.Getter方法访问.KVO 就是基于 KVC 实现的 ...

  8. Hybrid框架UI重构之路:六、前端那点事儿(Javascript)

    上文回顾 :Hybird框架UI重构之路:五.前端那点事儿(HTML.CSS) 这里讲述在开发的过程中,一些JS的关键点. 换肤 对于终端的换肤,我之前一篇文章有说了我的想法. 请查看:http:// ...

  9. Hybrid框架UI重构之路:五、前端那点事儿(HTML、CSS)

    上文回顾 :Hybird框架UI重构之路:四.分而治之 这里讲述在开发的过程中,一些HTML.CSS的关键点. 单页模式的页面结构 在单页模式中,弱化HTML的概念,把HTML当成一个容器,BODY中 ...

随机推荐

  1. 基于R-Tree的最近邻查询

    转自基于R-Tree的最近邻查询 BAB(Branch.and.Band)算法是由Nick Roussopoulousnl等人于1995年提出的,是最早的基于R.树的静态最近邻查询算法.该算法使用MI ...

  2. 发布ios应用程序

    详见文档 AppDistributionGuide Submit and Release Your App 首先,需要登入itunes connect并且输入必要的信息更改app状态为 waiting ...

  3. C# 把控件内容导出图片

    Bitmap newbitmap = new Bitmap(panelW.Width, panelW.Height);            panelW.DrawToBitmap(newbitmap ...

  4. 【String】String.format(format,args...)的使用解析

    String.format(format,args...)的使用解析 使用kotlin 中使用示例 ================================================== ...

  5. openfalcon的安装和使用

    蛮复杂的样子 根据官方文档指导,一步一步走起:https://book.open-falcon.org/zh_0_2/quick_install/prepare.html 单机安装的过程:单击安装会把 ...

  6. wiki平台工具

    1.  confluence  评点: 好用,与world类似.模板多.

  7. 适合新人学习的iOS官方Demo

    UICatalog.包括了绝大部分经常使用的UI,入门必备良药. 9  分段选择器 10滑动条 Slider 11stack view 12 分步条 13 开关 14 textfield 15text ...

  8. CSS3绘制灰太狼动画,绝对精彩

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. linux 环境 php 链接 sqlserver 2008

    说明 由于业务需要 在 linux 系统下的 PHP 环境中 要链接 sqlserver2008 数据库 . 添加PHP 链接数据库扩展 php-mssql dockerfile FROM hub.0 ...

  10. UFLDL教程(一)---稀疏自编码器

    神经网络模型 简单的神经网络 前向传播 代价函数 对于单个例子 .其代价函数为: 给定一个包括m个例子的数据集,我们能够定义总体代价函数为: 以上公式中的第一项  是一个均方差项. 第二项是一个规则化 ...