Reputation: 7510
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.
Upvotes: 8
Views: 2072
Reputation: 3017
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.
Upvotes: 12
Reputation: 29946
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.
Upvotes: 17