当你只有一个代理对象时,有什么方法可以测试选择器/方法吗?
/* Proxy which may forward
* the method to some other object */
id proxy = [UINavigationBar appearance];
/* This condition returns FALSE
* despite the fact that the method would have otherwise been
* successfully executed at its destination */
if([proxy respondsToSelector:@selector(setBarTintColor:)]){
[proxy setBarTintColor:color];
}
最佳答案
显然你不能。
其他答案建议的方法很容易坏,这里有一个例子:
UINavigationBar
实例响应选择器setTranslucent:
- 但是
setTranslucent:
在头文件中没有用UI_APPEARANCE_SELECTOR
标记
因此有如下代码
if([[UINavigationBar class] instancesRespondToSelector:@selector(setTranslucent:)]) {
[[UINavigationBar appearance] setTranslucent:NO]; // BUM!
}
会导致崩溃。
关于哪些选择器符合 UIAppearance
的唯一信息似乎是 UI_APPEARANCE_SELECTOR
宏,它在编译时被剥离。
运行时检查看起来不可行。
为了完整起见,这里有一个糟糕(但实用)的方法。
@try {
[[UINavigationBar appearance] setTranslucent:YES];
} @catch (NSException *exception) {
if ([exception.name isEqualToString:@"NSInvalidArgumentException"])
NSLog(@"Woops");
else
@throw;
}
但是,这非常脆弱,因为不能保证您只会捕捉到选择器不符合 UIAppearance
的情况。
关于ios - 如何在 Objective-C 中测试代理对象上的选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19057711/