KVC
KVC实际上是Key-Value Coding的简称,它是一种可以直接通过字符串的名字(key)来间接访问类属性(实例变量)的机制。
代码实现:
1 #import <Foundation/Foundation.h> 2 #import "Person.h" 3 #import "Dog.h" 4 5 int main(int argc, const char * argv[]) { 6 @autoreleasepool { 7 Person *xiaoming = [[Person alloc] init]; 8 9 //使用kvc设置变量的值 10 [xiaoming setValue:@"xm" forKey:@"name"]; 11 12 NSString *name = [xiaoming valueForKey:@"name"]; 13 NSLog(@"%@", name); 14 15 //确保狗是存在的 16 Dog *ww = [[Dog alloc] init]; 17 [xiaoming setValue:ww forKeyPath:@"dg"]; 18 19 [xiaoming setValue:@"汪汪" forKeyPath:@"dg.dogName"]; 20 NSLog(@"%@", [xiaoming valueForKeyPath:@"dg.dogName"]); 21 } 22 return 0; 23 }
kvc是一种间接的访问,这里特别要注意的是:key值,也就是变量的名字一定不可以写错!
KVO
Key-Value Observing的缩写,顾名思义就是一种观察、监控。它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
代码实现:(MRR)
#import "Person.h" @implementation Person - (void)dealloc{ [_card release]; [self removeObserver:self forKeyPath:@"card.money"]; [super dealloc]; } - (instancetype)init{ if (self = [super init]) { self.card = [[[CreditCard alloc] init] autorelease]; [self addObserver:self forKeyPath:@"card.money" options:NSKeyValueObservingOptionOld| NSKeyValueObservingOptionNew context:nil]; } return self; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ NSLog(@"old:%@", [change objectForKey:NSKeyValueChangeOldKey]); NSLog(@"new:%@", [change objectForKey:NSKeyValueChangeNewKey]); } @end