iPhone键值编码是否有办法测试一个类是否接受给定的键?
也就是说,如果没有实现目标类的valueForUndefinedKey:或setValue:forUndefinedKey:方法,我希望能够做到这样的事情:
if ([targetObject knowsAboutKey: key]) {
[targetObject setValue: value forKey: key];
}
答案 0 :(得分:4)
setValue的默认实现:forUndefinedKey:引发NSUndefinedKeyException。您可以在try / catch块中包围该尝试:
@try{
[targetObject setValue:value forKey:key];
} @catch (NSException *e) {
if ([[e name] isEqualToString:NSUndefinedKeyException]) {
NSLog(@"oh well... handle the case where it has no key here."); // handle
} else {
[[NSException exceptionWithName:[e name]
reason:[e reason]
userInfo:[e userInfo]]
raise];
}
}