【iOS 底层原理】KVC 本质原理

KVC 使用

KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性

常见的API有

  • (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
  • (void)setValue:(id)value forKey:(NSString *)key;
  • (id)valueForKeyPath:(NSString *)keyPath;
  • (id)valueForKey:(NSString *)key;

setValue:forKey:的原理

image.png

注:accessInstanceVariablesDirectly 方法的默认返回值是YES

setValue:forKey: 方法会先调用 setKey: 方法,如果没有,则调用带下划线的 _setKey: 方法。如果这两个方法都不存在,则调用 accessInstanceVariablesDirectly,accessInstanceVariablesDirectly 返回 NO 则抛出异常,accessInstanceVariablesDirectly 返回 YES,则按照 _key、_isKey、key、isKey 的顺序查找成员变量,找到成员变量,则直接赋值。

valueForKey:的原理

image.png

你可能感兴趣的:(【iOS 底层原理】KVC 本质原理)