当调用特定子类中可用的方法时,超类类别中的performSelector失败

esp*_*esp 0 objective-c uitextview nsattributedstring ios objective-c-category

我有UIView类,它定义了操纵attributedTextUILabel和UITextView属性的方法.

@implementation UIView (replaceAttrText)
-(void) replaceAttrText: (NSString *)str {
    if ([self respondsToSelector: @selector(setAttributedText)]) {
        NSMutableAttributedString *labelText = [self template];

        // change it

        [self performSelector:@selector(setAttributedText) withObject: labelText];
    }
}
@end
Run Code Online (Sandbox Code Playgroud)

对于UILabel和UITextView,respondsToSelector都返回false(尽管它们响应setAttributedText),如果直接执行setAttributedText而不respondsToSelector检查则引发异常.

当类别直接在UILabel上实现(没有选择器)时,一切正常,但遗憾的是UILabel和UITextView没有具有attributesText属性的共同祖先.

我究竟做错了什么?谢谢!

rma*_*ddy 5

UILabel并且UITextView没有名为的方法setAttributedText.但他们确实有一个名为的方法setAttributedText:.注意冒号.冒号是方法名称的一部分.拥有与否代表两种完全不同的方法.

将您的代码更改为:

-(void) replaceAttrText: (NSString *)str {
    if ([self respondsToSelector: @selector(setAttributedText:)]) {
        NSMutableAttributedString *labelText = [self template];

        // change it

        [self performSelector:@selector(setAttributedText:) withObject: labelText];
    }
}
Run Code Online (Sandbox Code Playgroud)

换句话说,在两个引用中添加一个冒号setAttributedText.

  • 正确的答案; 错误的模式.至少前缀该方法. (3认同)