Objective-C检测类是否覆盖继承的方法 [英] Objective-C detect if class overrides inherited method
问题描述
有没有办法在子类中动态检测它是否覆盖其父类方法?
Is there a way to dynamically detect from within a child class if its overriding its parents methods?
Class A {
- methodRed;
- methodGreen;
- methodBlue;
}
Class B inherits A {
- methodRed;
}
从上面的例子我想知道B类是否能够动态检测到只有 -methodRed;
被覆盖。
From the example above I would like to know if class B is able to dynamically detect that only -methodRed;
was overridden.
我想知道这种方法与其他一些可能性的原因是因为我有几十个自定义视图会改变它的外观。如果我可以动态检测被覆盖的方法而不是跟踪,那么代码将会少得多。
The reason am wondering about this approach versus some other possibilities is because I have dozens of custom views that will be changing there appearance. It would be a lot less code if I could dynamically detect the overridden methods versus keeping track.
推荐答案
这是相当简单的测试:
if (method_getImplementation(class_getInstanceMethod(A, @selector(methodRed))) ==
method_getImplementation(class_getInstanceMethod(B, @selector(methodRed))))
{
// B does not override
}
else
{
// B overrides
}
我不知道如何知道B是否覆盖A上的方法是有帮助的,但是如果你想知道,这就是你如何找到的。
I do have to wonder how knowing if B overrides a method on A is helpful, but if you want to know, this is how you find out.
它也可能值得注意:在最严格的条款中,上面的代码确定选择器的实现是否在B与A上的选择器的实现不同。如果你有一个像A> X> B和X覆盖选择器的层次结构,这仍然会报告A和B之间的不同实现,即使B不是如果你想特别知道B覆盖这个选择器(无论其他什么),你会想要这样做:
It also may be worth noting: In the strictest terms the above code determines whether the implementation for the selector on B is different from the implementation of the selector on A. If you had a hierarchy like A > X > B and X overrode the selector, this would still report different implementations between A and B, even though B wasn't the overriding class. If you want to know specifically "does B override this selector (regardless of anything else)" you would want to do:
if (method_getImplementation(class_getInstanceMethod(B, @selector(methodRed))) ==
method_getImplementation(class_getInstanceMethod(class_getSuperclass(B), @selector(methodRed))))
{
// B does not override
}
else
{
// B overrides
}
这显然可能会问B对选择器有不同的实现而不是超类,这是(或许更具体地说)你要求的。
This, perhaps obviously, asks the question "does B have a different implementation for the selector than its superclass" which is (perhaps more specifically) what you asked for.
这篇关于Objective-C检测类是否覆盖继承的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!