- (void)setValue:(id)value forKey:(NSString *)key
- (id)valueForKey:(NSString *)key
- (id)valueForKey:(NSString *)key //以 key 作为标示符,获取其对应的属性值
- (void)setValue:(id)value forKey:(NSString *)key //以 key 作为标示符设置其对应的属性值
- (id)valueForUndefinedKey:(NSString *)key
- (void)setNilValueForKey:(NSString *)key
```
Demo
创建一个QYPerson 类继承于 NSObject
QYPerson.h
```
#import <Foundation/Foundation.h>
@interface QYPerson : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
- (void)changeName;
@end
在 QYPerson.m 文件中实现上面的方法
#import "QYPerson.h"
@implementation QYPerson
- (void)changeName
{
_name = @"changeName";
}
@end
创建一个 QYPersonMonitor 的类用来监视 QYPerson 中的 name 属性
在. m 文件中实现对 QYPerson 中 name 属性的监视
#import "QYPersonMonitor.h"
@implementation QYPersonMonitor
// 2. 回调的方法 当观察的值改变的时候,该方法会被调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqual:@"name"]) {
NSLog(@"change name: old :%@, new : %@",[change objectForKey:NSKeyValueChangeOldKey],[change objectForKey:NSKeyValueChangeNewKey]);
}
}
@end
在控制器中初始化监视的对象以及被监视的对象,注册观察者
#import "ViewController.h"
#import "QYPerson.h"
#import "QYPersonMonitor.h"
@interface ViewController ()
@property (nonatomic, strong) QYPerson *person;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化被监视的对象
_person = [[QYPerson alloc] init];
_person.name = @"zhangsan";
_person.age = 18;
//监视对象
QYPersonMonitor *personMonitor = [[QYPersonMonitor alloc] init];
// 1. 注册了一个观察者
[_person addObserver:personMonitor forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
//初始化的值
NSLog(@"person‘s name is %@",_person.name);
//通过 setvalue 的方法,此时 QYPersonMonitor 的监视将被调用
[_person setValue:@"(lisi by KVC)" forKey:@"name"];
//打印通过 kvc 方式修改后的值
NSLog(@"person‘s name get by kvc is %@",[_person valueForKey:@"name"]);
//通过.语法修改的效果和通过 setvalue 是一致的
_person.name = @"name change by .name= wangwu";
//通过 person 自己的函数来更改 name 属性
[_person changeName];
}
@end
打印结果如下:
**2015-07-29 16:38:59.802 SetDemo[3764:1391043] person’s name is zhangsan
2015-07-29 16:38:59.802 SetDemo[3764:1391043] change name: old :zhangsan, new : (lisi by KVC)
2015-07-29 16:38:59.802 SetDemo[3764:1391043] person’s name get by kvc is (lisi by KVC)
2015-07-29 16:38:59.802 SetDemo[3764:1391043] change name: old :(lisi by KVC), new : name change by .name= wangwu**
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/www_nyp_boke/article/details/47156575