iOS开发 KVC与KVO

KVC

About Key-Value Coding
Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface. This indirect access mechanism supplements the direct access afforded by instance variables and their associated accessor methods.

译:键值编码是一种由NSKeyValueCoding非正式协议所支持的机制,对象采用该协议来提供对其属性的间接访问。当一个对象的键值编码兼容时,它的属性通过一个简洁的、统一的消息传递接口通过字符串参数寻址。这种间接访问机制补充了实例变量及其相关访问方法所提供的直接访问。

You typically use accessor methods to gain access to an object’s properties. A get accessor (or getter) returns the value of a property. A set accessor (or setter) sets the value of a property. In Objective-C, you can also directly access a property’s underlying instance variable. Accessing an object property in any of these ways is straightforward, but requires calling on a property-specific method or variable name. As the list of properties grows or changes, so also must the code which accesses these properties. In contrast, a key-value coding compliant object provides a simple messaging interface that is consistent across all of its properties.

译:您通常使用访问器方法来访问对象的属性。获取访问器(或getter)返回属性的值。设置访问器(或setter)设置属性的值。在Objective-C中,还可以直接访问属性的底层实例变量。在任何一种方法中访问对象属性都很简单,但是需要调用特定于属性的方法或变量名。随着属性列表的增长或变化,访问这些属性的代码也必须如此。相反,一个键值编码兼容的对象提供了一个简单的消息接口,它在所有属性中都是一致的。

Key-value coding is a fundamental concept that underlies many other Cocoa technologies, such as key-value observing, Cocoa bindings, Core Data, and AppleScript-ability. Key-value coding can also help to simplify your code in some cases.

译:键值编码是基础概念,它支持许多其他的Cocoa技术,如键值观察、Cocoa绑定、Core Data和apples- ability。在某些情况下,键值编码还可以帮助简化代码。

KVC是Key Value Coding的缩写,即键值编码。在iOS的开发中,可以通过key名直接访问实例对象的属性,而不需要调用明确的存取方法。

也就是说我们可以在程序运行时动态地访问和修改对象的属性。KVC的定义都是对NSObject的扩展来实现的NSObject(NSKeyValueCoding),所以对于所有继承了NSObject的类型,都能使用KVC

看看苹果API给的解释

valueForKey:
  • Search the instance for the first accessor method found with a name like get<Key>, <key>, is<Key>, or _<key>, in that order. If found, invoke it and proceed to step 5 with the result. Otherwise proceed to the next step.
  • If no simple accessor method is found, search the instance for methods whose names match the patterns countOf<Key> and objectIn<Key>AtIndex: (corresponding to the primitive methods defined by the NSArray class) and <key>AtIndexes: (corresponding to the [NSArray](https://developer.apple.com/library/archive/documentation/LegacyTechnologies/WebObjects/WebObjects_3.5/Reference/Frameworks/ObjC/Foundation/Classes/NSArrayClassCluster/Description.html#//apple_ref/occ/cl/NSArray)method objectsAtIndexes:).
    If the first of these and at least one of the other two is found, create a collection proxy object that responds to all NSArray methods and return that. Otherwise, proceed to step 3.
    The proxy object subsequently converts any NSArray messages it receives to some combination of countOf<Key>, objectIn<Key>AtIndex:, and <key>AtIndexes: messages to the key-value coding compliant object that created it. If the original object also implements an optional method with a name like get<Key>:range:, the proxy object uses that as well, when appropriate. In effect, the proxy object working together with the key-value coding compliant object allows the underlying property to behave as if it were an NSArray, even if it is not.
  • If no simple accessor method or group of array access methods is found, look for a triple of methods named countOf<Key>, enumeratorOf<Key>, and memberOf<Key>: (corresponding to the primitive methods defined by the [NSSet](https://developer.apple.com/library/archive/documentation/LegacyTechnologies/WebObjects/WebObjects_3.5/Reference/Frameworks/ObjC/Foundation/Classes/NSSetClassCluster/Description.html#//apple_ref/occ/cl/NSSet) class).
    If all three methods are found, create a collection proxy object that responds to all NSSetmethods and return that. Otherwise, proceed to step 4.
    This proxy object subsequently converts any NSSet message it receives into some combination of countOf<Key>, enumeratorOf<Key>, and memberOf<Key>: messages to the object that created it. In effect, the proxy object working together with the key-value coding compliant object allows the underlying property to behave as if it were an NSSet, even if it is not.
  • If no simple accessor method or group of collection access methods is found, and if the receiver's class method [accessInstanceVariablesDirectly](https://developer.apple.com/library/archive/documentation/LegacyTechnologies/WebObjects/WebObjects_3.5/Reference/Frameworks/ObjC/EOF/EOControl/Classes/NSObjectAdditions/Description.html#//apple_ref/occ/clm/NSObject/accessInstanceVariablesDirectly) returns YES, search for an instance variable named _<key>, _is<Key>, <key>, or is<Key>, in that order. If found, directly obtain the value of the instance variable and proceed to step 5. Otherwise, proceed to step 6.
  • If the retrieved property value is an object pointer, simply return the result.
    If the value is a scalar type supported by NSNumber, store it in an NSNumber instance and return that.
    If the result is a scalar type not supported by NSNumber, convert to an NSValue object and return that.
  • If all else fails, invoke [valueForUndefinedKey:](https://developer.apple.com/documentation/objectivec/nsobject/1413457-value). This raises an exception by default, but a subclass of NSObject may provide key-specific behavior.
  1. 按顺序搜索访问器方法get<Key>/<key>/is<Key>/_<key>。如果找到,调用该方法并且带着方法的调用结果调转到第5步执行;否则,继续下一步。
  2. 如果没有找到简单的访问方法,搜索其名称匹配某些模式的方法的实例。其中匹配模式包含countOf<Key>,objectIn<Key>AtIndex:(对应于NSArray定义的基本方法),和<key>AtIndexs:(对应于NSArray的方法objectsAtIndexs:)一旦找到第一个和其他两个中的至少一个,则创建一个响应所以NSArray方法并返回该方法的集合代理对象。否则,执行第3步。
    代理对象随后将任何NSArray接收到的一些组合的消息。实际上,与符合键值编码对象一起工作的代理对象允许底层属性的行为就像它是NSArray一样,即便它不是。
  3. 如果没有找到简单的访问器方法或数组访问方法组,则寻找三个方法countOf<Key>/enumeratorOf<Key>/memberOf<Key>:,对应NSSet类的基本方法。
  4. 如果三个方法全找到了,则创建一个集合代理对象来响应所有的NSSet方法并返回。否则,执行第4步。如果上面的方法都没有找到,并且接受者的类方法accessInstanceVariablesDirectly返回YES(默认YES),则按序搜索以下实例变量:_<key>/_is<Key>/<key>/is<Key>。如果找到其中之一,直接获取实例变量的值并跳转到第5步;否则执行第6步。
  5. 如果检索到的属性值是对象指针,则只返回结果;如果值是受NSNumber支持的标量,则将其存储在NSNumber实例中并返回;如果结果是NSNumber不支持的标量,则转换成NSValue对象并返回
  6. 如果以上所有的尝试都失败了,则调用valueForUndefinedKey:,这个方法默认抛出异常,NSObject的子类可以重写来自定义行为。
setValue:
  • Look for the first accessor named set<Key>: or _set<Key>, in that order. If found, invoke it with the input value (or unwrapped value, as needed) and finish.
  • If no simple accessor is found, and if the class method accessInstanceVariablesDirectly returns YES, look for an instance variable with a name like _<key>, _is<Key>, <key>, or is<Key>, in that order. If found, set the variable directly with the input value (or unwrapped value) and finish.
  • Upon finding no accessor or instance variable, invoke setValue:forUndefinedKey:. This raises an exception by default, but a subclass of NSObject may provide key-specific behavior.
  1. 按序搜索set<Key>:或_set<Key>,如果找到,则使用输入参数调用并结束。
  2. 如果没有找到简单的访问器方法,并且如果类方法accessInstanceVariablesDirectly返回YES(默认为YES),则按序搜索以下实例变量: _<key>/_is<Key>/<key>/is<Key>,如果找到了则直接进行赋值并结束。
  3. 以上方法皆失败则调用setValue:forUndefinedKey:,这个方法默认抛出异常,NSObject的子类可以自定义。
参考资料

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueCoding/index.html

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,257评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 11,499评论 2 19
  • 曾经我也是个被吼,小孩子家家哪有什么腰的孩子。 所以,我觉得,如果长大的时候,绝不做这样伤人心的大人。 被说没有腰...
    南茶暖阅读 532评论 0 3
  • 今天下午,我去学口才。我们到了那里一人发了一张纸,纸上有几个词,分别是:一声的词、二声的的词,三声的词...
    刘俊艳阅读 226评论 0 0
  • 浏览回顾一周。 上周的周五~周日,苏州理财规划师考试的考前课。 周日也是母亲生日。 周一,上海,与表姐增进情感 周...
    ShirleyZH阅读 239评论 0 0