什么是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. Adding an Exception Breakpoint - Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 25 bey

    用如下的方法可以非常方便停留到具体crash的某行代码 Adding an Exception Breakpoint Add an exception breakpoint to your proje ...

  2. K8S label 操作

    在部署完成 node 节点集群之后,为了更灵活的操控 node 节点,有时候需要对 node 节点进行对各个 node 节点进行 lable 标签标记. 查看各个节点的信息 [root@porxy02 ...

  3. discuz搬家

    1.需要重命名forumdata下面的cache和templates文件夹 2.如果数据库账户名和密码有改动过,需要修改config.inc.php 3.保证uc_server的链接正确!

  4. BUPT复试专题—哈夫曼树(2010)

    https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155?tpId=67&tqId=29635&tPage= ...

  5. chrome插件网站

    chrome插件网站 http://chromecj.com/

  6. 怎样改动X-code中的字体大小、颜色

  7. 跟着实例学习设计模式(7)-原型模式prototype(创建型)

    原型模式是创建型模式. 设计意图:用原型实例指定创建对象的类型,并通过拷贝这个原型来创建新的对象. 我们使用构建简历的样例的类图来说明原型模式. 类图: 原型模式主要用于对象的复制.它的核心是就是类图 ...

  8. linux下查看网卡信息的命令

    rhel 内核版本号信息: [root@hvrhub ~]# uname -a Linux hvrhub 2.6.18-308.el5 #1 SMP Fri Jan 27 17:17:51 EST 2 ...

  9. 【转载】分布式RPC框架性能大比拼

    dubbo.motan.rpcx.gRPC.thrift的性能比较 Dubbo 是阿里巴巴公司开源的一个Java高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,可以和 ...

  10. vim note (1)

    'vim' go into the vim mode 'i' 'a' 's'    is means insert mode 'v' is means visual mode 'esc' is mea ...