虽然我想不出一种方法来找出对象支持哪些键,但您可以使用这样一个事实,即当您为不存在的键设置值时,对象的默认行为是抛出异常。您可以将setValue:forKey:
方法调用包含在@try
/@catch
块中以处理这些错误。
考虑以下对象的代码:
@interface KVCClass : NSObject {
NSString *stuff;
}
@property (nonatomic, retain) NSString *stuff;
@end
@implementation KVCClass
@synthesize stuff;
- (void) dealloc
{
[stuff release], stuff = nil;
[super dealloc];
}
@end
这应该与密钥的 KVC 兼容,stuff
但仅此而已。
如果您从以下程序访问此类:
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
KVCClass *testClass = [[KVCClass alloc] init];
[testClass setValue:@"this is the value" forKey:@"stuff"];
NSLog(@"%@", testClass.stuff);
// Error handled nicely
@try {
[testClass setValue:@"this should fail but we will catch the exception" forKey:@"nonexistentKey"];
}
@catch (NSException * e) {
NSLog(@"handle error here");
}
// This will throw an exception
[testClass setValue:@"this will fail" forKey:@"nonexistentKey"];
[testClass release];
[pool drain];
return 0;
}
您将获得类似于以下内容的控制台输出:
2010-01-08 18:06:57.981 KVCTest[42960:903] this is the value
2010-01-08 18:06:57.984 KVCTest[42960:903] handle error here
2010-01-08 18:06:57.984 KVCTest[42960:903] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<KVCClass 0x10010c680> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key nonexistentKey.'
*** Call stack at first throw:
(
0 CoreFoundation 0x00007fff851dc444 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x00007fff866fa0f3 objc_exception_throw + 45
2 CoreFoundation 0x00007fff85233a19 -[NSException raise] + 9
3 Foundation 0x00007fff85659429 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 434
4 KVCTest 0x0000000100001b78 main + 328
5 KVCTest 0x0000000100001a28 start + 52
6 ??? 0x0000000000000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
Abort trap
这表明第一次访问密钥的尝试nonexistentKey
被程序很好地捕获,第二次尝试生成与您的类似的异常。