iPhone键值编码--测试键是否存在

7

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

也就是说,不需要实现目标类的valueForUndefinedKey:或setValue:forUndefinedKey:方法,我想能够做到这样:

if ([targetObject knowsAboutKey: key])  {
  [targetObject setValue: value forKey: key];
}
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]; 
    } 
}

3
实际上,NSUndefinedKeyException不是一个类,它只是一个字符串。因此,为了正确处理它,我使用了"@catch (NSException *e) { if ([[e name] isEqualToString:NSUndefinedKeyException]) { ; // handle } else { [[NSException exceptionWithName:[e name] reason:[e reason] userInfo:[e userInfo]] raise]; } }"的代码。 - mrueg
有没有想过在Swift中如何捕获这个异常? - devios1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接