问题描述
是否可以检查子类是否实现了一个存在于其直接超类或其超类的某些超类中的方法等?
Is it possible to check whether a subclass implements a method that exists either in its immediate superclass or in some superclass of its superclass, etc?
例如。我继承 UIView
,为我的应用程序创建自定义通用视图,然后我将此自定义视图子类化。现在,我的一些子类会覆盖 UIView
中的某些方法,而有些则不会。我只想调用此方法,如果它实际被覆盖,我不希望调用默认的 UIView
方法。
E.g. I subclass UIView
, to make my custom generic view for my app, and then I subclass this custom view. Now some of my subclasses override some method from UIView
and some don't. I only want to call this method if it is actually overridden, I do not want the default UIView
method being called.
有没有办法检查这个,即使用类似于的方法respondsToSelector:
?
Is there a way to check this, i.e. with a method similar to respondsToSelector:
?
修改:
此问题与因为我真的不知道或者不想关心哪个超类最初实现该方法。
This question is different from the one asked in Objective-C detect if class overrides inherited method because I do not really know or do not want to care which superclass originally implements the method.
推荐答案
基于此回答作者:Mert Buran。
Based on this answer by Mert Buran.
您可以创建一个简单的方法来检查给定对象是否覆盖给定的选择器(方法):
You can create a simple method to check whether a given object overrides a given selector (method):
-(BOOL)checkIfObject:(id)object overridesSelector:(SEL)selector {
Class objSuperClass = [object superclass];
BOOL isMethodOverridden = NO;
while (objSuperClass != Nil) {
isMethodOverridden = [object methodForSelector: selector] !=
[objSuperClass instanceMethodForSelector: selector];
if (isMethodOverridden) {
break;
}
objSuperClass = [objSuperClass superclass];
}
return isMethodOverridden;
}
可以按如下方式调用:
[self checkIfObject:someObject overridesSelector:@selector(someSelector)];
这篇关于检查子类是否覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!