Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone key-value coding -- test for existence of key

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];
}
like image 522
William Jockusch Avatar asked Oct 08 '10 15:10

William Jockusch


1 Answers

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]; 
    } 
}
like image 197
kevboh Avatar answered Oct 13 '22 00:10

kevboh