Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...