7

iPhone の key-value-coding には、クラスが特定のキーを受け入れるかどうかをテストする方法がありますか?

つまり、ターゲット クラスの 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 に答える