简介
- KVO 与KVC 是 充分利用了objective-c 动态语言特性的一种机制
KVO(同步运行)
//注册通知
- (void)addObserver:(NSObject *)anObserver
forKeyPath:(NSString *)keyPath
options:(NSKeyValueObservingOptions)options
context:(void *)context
//接受通知,做出回应
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
KVC
@property (nonatomic, copy) NSString *name;
//取值
NSString *n = [object valueForKey:@"name"]
//赋值
[object setValue:@"Daniel" forKey:@"name"]
//KVC 同样允许我们通过关系来访问对象。假设 person 对象有属性 address,address 有属性 city,我们可以这样通过 person 来访问 city:
[person valueForKeyPath:@"address.city"]