7

iPhone键值编码是否有办法测试一个类是否会接受给定的键?

也就是说,在不实现目标类的 valueForUndefinedKey: 或 setValue: forUndefinedKey: 方法的情况下,我希望能够执行以下操作:

if ([targetObject knowsAboutKey: key])  {
  [targetObject setValue: value forKey: key];
}
4

1 回答 1

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]; 
    } 
}
于 2010-10-08T17:55:41.063 回答