在哪些情况下对象不符合键值编码?
目前我正在学习有关键值编码的所有内容。
他们在文档中说:
关键路径序列中的任何对象 不符合键值编码 对于适当的密钥接收 valueForUndefinedKey:消息。
我尝试想象一个对象不符合键值编码的情况。 怎么会发生这种事? 当我子类化 UIView 时,这显然是合规的,对吧? 但是当我用 NSObject 作为超类创建自己的对象时,怎么样? 当我创建一个没有超类的类时,那么这肯定不符合 kv 要求吗?
Currently I'm learning all the stuff around key-value coding.
In the docs they say:
Any object in the key path sequence
that is not key-value coding compliant
for the appropriate key receives a
valueForUndefinedKey: message.
I try to imagine a situation where an object is not key-value coding compliant. How could that happen? When I subclass an UIView, that's obviously compliant, right? But when I just make my own object with NSObject as superclass, how's that? And when I make a class with no superclass, then for sure this is not k-v compliant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你仔细阅读,你会看到它说“键值编码符合适当的键”。 这基本上意味着您没有适合您所需密钥的 KVC 方法。 因此,如果我执行
[[NSString stringWithString:@"foo"] valueForKey:@"dippingSauce"]
,它将落入valueForUndefinedKey:
因为 NSString 不符合 KVC 标准对于键“dippingSauce” - 它没有dippingSauce
实例方法或dippingSauce
ivar。If you read carefully, you'll see it says "key-value coding compliant for the appropriate key". This means, basically, that you don't have the appropriate KVC methods for the key you asked for. So if I do
[[NSString stringWithString:@"foo"] valueForKey:@"dippingSauce"]
, it will fall through tovalueForUndefinedKey:
because NSString is not KVC-compliant for the key "dippingSauce" — it doesn't have adippingSauce
instance method or adippingSauce
ivar.它说“对于适当的键来说,这不符合键值编码”。 这意味着它
符合“foo”和“bar”,但不符合“baz”。
对于简单的属性来说,默认情况下所有 NSObject 子类都实现基本的 KVC。 对于集合来说,事情变得更加棘手。 为了让 KVC 能够正确地处理集合(因此您可以执行以下操作:
它需要您实现某些额外的方法。一般来说,该功能的最大用户是源自 CoreData 的 Cocoa 绑定(在 iPhone 上不可用)(无论如何,它会自动生成额外的集合方法),因此通常人们不会费心在其对象中实现对字典或数组的完整 KVC 支持,除非他们打算实际公开它们。 “http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/Compliant.html” rel="nofollow noreferrer">阅读 KVC 指南中有关合规性的信息。
It says "that is not key-value coding compliant for the appropriate key." What that means is that
Is compliant for "foo" and "bar", but not "baz."
For simple properties that is all there is to it, by default all NSObject subclasses implement basic KVC. It gets trickier with collections. In order for KVC to work correctly for collections (so you can do things like:
It requires you implement certain extra methods. In general the biggest user of that functionality is Cocoa bindings (which is not available on the iPhone) sourced out of CoreData (which generates that additional collection methods automatically anyway), so it still usually handled basically automatically. Generally people don't bother to implement full KVC support for dictionaries or arrays in their objects unless they intend to actually expose them. You can read about compliance in the KVC guide.