1. KVC的使用
- 相关API
/// 赋值 -(void)setValue:(id)value forKeyPath:(NSString *)keyPath; -(void)setValue:(id)value forKey:(NSString *)key; /// 取值 -(id)valueForKeyPath:(NSString *)keyPath; -(id)valueForKey:(NSString *)key; - 假设当前有Person和Cat类
#import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic, assign) int age; @property (nonatomic, strong) Cat cat; @end @interface Cat : NSObject @property (nonatomic, assign) int weight; @end keyPath和key的区别?-
keyPath的功能包含key,如下所示有相同效果:Person *person = [Person new]; /// 赋值 [person setValue:@(10) forKey:@"age"]; [person setValue:@(10) forKeyPath:@"age"]; /// 取值 [person valueForKey:@"age"]; [person valueForKeyPath:@"age"]; -
keyPath还可以指定路径进行取值和赋值:/// 赋值 [person setValue:@(10) forKeyPath:@"cat.weight"]; /// 取值 [person valueForKeyPath:@"cat.weight"];
-
2. KVC赋值的原理
- 流程:
- 问题:KVC是否会触发KVO?
- 进行验证:
self.person = [Person new]; [self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; [self.person setValue:@(10) forKey:@"age"];- 验证结果为:会进入
observeValueForKeyPath监听方法
+ (BOOL)accessInstanceVariablesDirectly;- 是否允许访问成员变量