Objective-C detects class overrides inherited method

Is there a way to dynamically detect from within a child class if it overrides its parents' methods?

Class A { - methodRed; - methodGreen; - methodBlue; } Class B inherits A { - methodRed; } 

In the above example, I would like to know if class B can dynamically detect that only -methodRed; has been redefined.

The reason I am asking this question compared to some other features is because I have dozens of user views that will change there. There would be much less code if I could dynamically detect overridden methods and track tracking.

+6
source share
2 answers

This is pretty simple to check:

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

I need to wonder if it is useful to know that B overrides the method on A, but if you want to know this, here's how you find out.

It may also be worth noting: in the strict sense, the code above determines whether the implementation of the selector differs from B from the implementation of the selector by A. If you had a hierarchy A> X> B and X overriding the selector, it will still report different implementations between A and B, although B is not an override class. If you want to know for sure that "B cancels this selector (regardless of anything else)", you would like 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: โ€œB has a different implementation for the selector than its superclass,โ€ which (perhaps more specifically) is what you asked for.

+16
source

In your base class:

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

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

The answers above are also correct, but it may look better.

+11
source

Source: https://habr.com/ru/post/947468/


All Articles