3

目前我正在学习有关键值编码的所有内容。

他们在文档中说:

键路径序列中的任何不符合相应键的键值编码的对象都会收到 valueForUndefinedKey: 消息。

我试着想象一个对象不符合键值编码的情况。怎么会这样?当我子类化 UIView 时,这显然是合规的,对吧?但是当我只是用 NSObject 作为超类创建自己的对象时,那是怎么回事?当我创建一个没有超类的类时,那么确定这不符合 kv 吗?

4

2 回答 2

8

如果你仔细阅读,你会看到它说“key-value coding compatible for the appropriate key ”。基本上,这意味着您没有针对您要求的密钥的适当 KVC 方法。因此,如果我这样做[[NSString stringWithString:@"foo"] valueForKey:@"dippingSauce"],它将失败,valueForUndefinedKey:因为 NSString 对于键“dippingSauce”不兼容 KVC——它没有dippingSauce实例方法或dippingSauceivar。

于 2009-07-22T08:42:43.527 回答
4

它说“这不符合适当的键值编码。” 这意味着

@interface MyObject : NSObject {
  NSString *foo;
  NSString *bar;
}

@property (nonatomic, retain) NSString *foo;
@property (nonatomic, retain) NSString *bar;

@end

@interface MyObject

@synthesize foo;
@synthesize bar;

@end

符合“foo”和“bar”,但不符合“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:

NSArray *people = ... ;
NSArray *firstNames = [people valueForKey:@"firstName"];

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.

于 2009-07-22T08:44:44.303 回答