KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性
KVC主要用到的方法
- (void)setValue:(id)value forKey:(NSString *)key;
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (id)valueForUndefinedKey:(NSString *)key
KVC赋值的流程

KVC取值的流程

示例代码
@interface TBStudent : NSObject
@property (nonatomic, assign) int number;
@end
@implementation TBStudent
@end
@interface TBPerson : NSObject
{
@public
NSString *name;
}
@property (nonatomic, strong) TBStudent *student;
@end
@implementation TBPerson
- (void)willChangeValueForKey:(NSString *)key{
[super willChangeValueForKey:key];
NSLog(@"willChangeValueForKey:%@",key);
}
- (void)didChangeValueForKey:(NSString *)key{
NSLog(@"didChangeValueForKey:%@ --- begin",key);
[super didChangeValueForKey:key];
NSLog(@"didChangeValueForKey:%@ --- end",key);
}
+ (BOOL)accessInstanceVariablesDirectly{
return YES;
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
TBPerson *person = [[TBPerson alloc] init];
person->name = @"11";
person.student = [[TBStudent alloc] init];
NSKeyValueObservingOptions options = NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew;
[person addObserver:self forKeyPath:@"name" options:options context:nil];
[person setValue:@"22" forKey:@"name"];
[person setValue:@33 forKeyPath:@"student.number"];
NSLog(@"TBPerson -- name:%@",[person valueForKey:@"name"]);
NSLog(@"TBStudent -- number:%@",[person valueForKeyPath:@"student.number"]);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"监听到%@的%@属性由%@变化为%@",object,keyPath,change[NSKeyValueChangeOldKey],change[NSKeyValueChangeNewKey]);
}
@end
KVC[85973:4686513] willChangeValueForKey:name
KVC[85973:4686513] didChangeValueForKey:name --- begin
KVC[85973:4686513] 监听到<TBPerson: 0x600001a9c2c0>的name属性由11变化为22
KVC[85973:4686513] didChangeValueForKey:name --- end
KVC[85973:4686513] TBPerson -- name:22
KVC[85973:4686513] TBStudent -- number:33
============================== 补充 ==============================
1、KVC赋值的过程猜测
1.1、[self willChangeValueForKey:@"name"];
1.2、修改成员变量的值
1.3、[self didChangeValueForKey:@"name"];
1.3.1、didChangeValueForKey:方法里面做的操作(通知监听器)
[observe observeValueForKeyPath:@"name" ofObject:self change:nil context:nil];
** 由KVC的赋值过程可以判断 --- 通过KVC修改属性(成员变量)的值是会触发KVO的;
PS 此文为学习 李明杰 老师的 iOS底层原理课程 所写笔记