iPhone键值编码 - 测试键的存在

Wil*_*sch 7 iphone key-value-coding

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

也就是说,如果没有实现目标类的valueForUndefinedKey:或setValue:forUndefinedKey:方法,我希望能够做到这样的事情:

if ([targetObject knowsAboutKey: key])  {
  [targetObject setValue: value forKey: key];
}
Run Code Online (Sandbox Code Playgroud)

kev*_*boh 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]; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,NSUndefinedKeyException不是一个类,而只是一个字符串。因此,为了做正确的事情,我使用 `@catch (NSException *e) { if ([[e name] isEqualToString:NSUndefinedKeyException]) { ; // 处理 } else { [[NSException exceptionWithName:[e name] Reason:[e Reason] userInfo:[e userInfo]] raise]; } }` (3认同)