- (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
@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**