如何覆盖新功能并使其向后兼容?

时间:2014-03-27 22:07:11

标签: ios objective-c cocoa-touch inheritance override

我想覆盖setTintColor:子类的UIView函数。在iOS 7中执行此操作没有问题,因为该功能是从该版本开始引入的。但是,我无法弄清楚如何使此功能向后兼容iOS 6.以下内容将崩溃。

- (void)setTintColor:(UIColor *)tintColor
{
    if ([super respondsToSelector:@selector(setTintColor:)]) {
        // Crashes here with "unrecognized selector" in iOS 6, probably because 
        // defining setTintColor: makes respondsToSelector: return YES for all
        // objects in the hiearchy regardless of whether it is defined at its
        // level.
        [super setTintColor:tintColor];
    }
    self.label.textColor = tintColor;
    self.dividerLeft.backgroundColor = tintColor;
    self.dividerRight.backgroundColor = tintColor;
}

1 个答案:

答案 0 :(得分:2)

您可以将条件更改为此

if ([UIView instancesRespondToSelector:(setTintColor:)])

您的代码无法运行的原因是因为super只是self的特殊版本,并且由于您的子类响应setTintColor:,它将返回YES。