KVC(Key-Value Coding),允许开发者通过key或者keyPath直接访问对象的属性,或者为对象的属性赋值而不用调用明确的存取方法
// NSObject的NSKeyValueCoding分类提供了KVC的相关方法
@interface NSObject(NSKeyValueCoding)
- (nullable id)valueForKey:(NSString *)key;
- (void)setValue:(nullable id)value forKey:(NSString *)key;
- (nullable id)valueForKeyPath:(NSString *)keyPath;
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;
- (BOOL)validateValue:(inout id _Nullable * _Nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
- (nullable id)valueForUndefinedKey:(NSString *)key;
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;
- (void)setNilValueForKey:(NSString *)key;
...
@end
KVC的使用
@interface
KVC的过程
-valueForKey:
-
查询对象是否有符合
-get<Key>
,-<key>
或者-is<Key>
的方法,如果有,则直接调用并返回;否则进入下一步。
PREVIOUSObjective-c NSProxy