Objective-C detect if class overrides inherited method

穿精又带淫゛_ 提交于 2019-11-29 07:12:13

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.

Mert Buran

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.

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