KVC的全程是 Key-Value Coding
,俗称键值编码
,可以通过一个Key
来访问某个属性
常用的API有
- (void)setValue:(nullable id)value forKey:(NSString *)key;
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;
- (nullable id)valueForKey:(NSString *)key;
- (nullable id)valueForKeyPath:(NSString *)keyPath;
setValue:forKey:
的原理
按照setKey:
、_setKey:
顺序查找方法,如果找到了就传递参数,调用方法,找不到方法就会调用setValue:forUndefinedKey:
,只要实现了这个方法就不会抛出异常
类方法 accessInstanceVariablesDirectly
返回YES
的时候,在没有找到setKey:
、_setKey:
方法时,会继续查找_key
、_isKey
、key
、isKey
的顺序方式去找成员变量
valueForKey:
的原理
按照getKey
key
isKey
_key
的顺序查找方法,找到了就直接调用,没有找到,查看accessInstanceVariablesDirectly
的返回值,如果返回YES
,按照_key
、_isKey
、key
、isKey
的顺序查找成员变量,找到了直接取值;如果返回NO
,直接调用setValue:forUndefinedKey:
抛出异常,如果实现了这个方法不抛出异常
网友评论