Objective-C detect if class overrides inherited method

青春壹個敷衍的年華 提交于 2019-11-28 00:42:49

问题


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;
}

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.


回答1:


This is fairly straightforward to test:

if (method_getImplementation(class_getInstanceMethod(A, @selector(methodRed))) ==
    method_getImplementation(class_getInstanceMethod(B, @selector(methodRed))))
{
    // B does not override
}
else
{
    // B overrides
}

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.

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
}

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.




回答2:


Within your base class:

BOOL isMethodXOverridden = [self methodForSelector:@selector(methodX)] !=
                           [BaseClass instanceMethodForSelector:@selector(methodX)];

will give you YES if methodX is overridden by your subclass.

Answers above are also right but that may look better.



来源:https://stackoverflow.com/questions/17147203/objective-c-detect-if-class-overrides-inherited-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!