respondsToSelector在UIButton上返回"setTitle:"的YES,但没有这样的选择器



我正在使用respondsToSelector:,大多数时候它工作正常。但是有一种情况我得到错误的结果:

UIButton* button = [[UIButton alloc] init];
if([button respondsToSelector:NSSelectorFromString(@"setTitle:")]) // returns YES
{
    // try to call "setTitle:"
}

respondsToSelector:返回 YES,但 UIButton 类中没有setTitle:选择器。有setTitle:forState:选择器,但这绝对不一样。

那么为什么respondsToSelector:返回是呢?

响应选择器不仅会检查公共接口,还会采用它能找到的任何方法。我不记得UIButton的早期 API 是否直接公开了标题,但在内部,随着状态的变化,它可能会被调用。

尝试只对实际需要验证的 API 使用respondsToSelector:,并注意通常有私有 API 后来被公开,这也可能导致有趣的情况......

Alexandr, 只有当你想检查一个对象是否实现了你要调用的方法时,你才应该使用这个"respondsToSelector"方法。对于设置按钮标题,为什么需要使用它?

您应该使用此方法,通常您正在使用自定义委托方法。

最新更新