ios - 如何在 Objective-C 中测试代理对象上的选择器?

标签 ios objective-c uiappearance respondstoselector

当你只有一个代理对象时,有什么方法可以测试选择器/方法吗?

/* 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/

相关文章:

iOS 发布 Twitter 媒体崩溃

objective-c - 核心文本(OS X 和 iOS)和 TeX

ios - MFMessageComposeViewController 外观 iOS 7

ios - UIAppearance setTranslucent error : Illegal property type, c for appearance setter, _installAppearanceSwizzleForSetter

ios - 来自轻弹 Action 和 UIPanGestureRecognizer 的意外结果

ios - 使用 UIAppearance 设置 View Controller 的直接 View 背景颜色

iphone - 在不使用 Internet 的情况下获取下一分钟时间 (UTC)

ios - 更改 ViewController Swift 的背景颜色? (单 View 应用程序)

ios - ios悬停事件的问题

ios - 如何在不降低其质量的情况下保存 UIView 内容(屏幕截图)