KVC
KVC实际上是Key-Value Coding的简称,它是一种可以直接通过字符串的名字(key)来间接访问类属性(实例变量)的机制。
代码实现:
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *xiaoming = [[Person alloc] init];
//使用kvc设置变量的值
[xiaoming setValue:@"xm" forKey:@"name"];
NSString *name = [xiaoming valueForKey:@"name"];
NSLog(@"%@", name);
//确保狗是存在的
Dog *ww = [[Dog alloc] init];
[xiaoming setValue:ww forKeyPath:@"dg"];
[xiaoming setValue:@"汪汪" forKeyPath:@"dg.dogName"];
NSLog(@"%@", [xiaoming valueForKeyPath:@"dg.dogName"]);
}
return 0;
}
P.S. kvc是一种间接的访问,这里特别要注意的是:key值,也就是变量的名字一定不可以写错!#
KVO
Key-Value Observing的缩写,顾名思义就是一种观察、监控。它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
代码实现:(MRC)
#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