Search code examples
iphonekey-value-coding

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];
}

Solution

  • 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]; 
        } 
    }