7

Does iPhone key-value-coding have a way to test whether a class will accept a given key?

That is, without implementing the valueForUndefinedKey: or setValue: forUndefinedKey: method of the target class, I want to be able to do something like this:

if ([targetObject knowsAboutKey: key])  {
  [targetObject setValue: value forKey: key];
}
William Jockusch
  • 26,513
  • 49
  • 182
  • 323

1 Answers1

4

The default implementation of setValue:forUndefinedKey: raises an NSUndefinedKeyException. You could surround the attempt in a try/catch block:

@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]; 
    } 
}
Lukasz 'Severiaan' Grela
  • 6,078
  • 7
  • 43
  • 79
kevboh
  • 5,207
  • 5
  • 38
  • 54
  • 3
    Actually, NSUndefinedKeyException is not a class, but just a string. So, to do the right thing, I use `@catch (NSException *e) { if ([[e name] isEqualToString:NSUndefinedKeyException]) { ; // handle } else { [[NSException exceptionWithName:[e name] reason:[e reason] userInfo:[e userInfo]] raise]; } }` – mrueg Jun 12 '13 at 14:06
  • Any idea how to catch this exception in Swift?? – devios1 Feb 01 '16 at 18:57