7

How can I find out, at runtime, if a class overrides a method of its superclass?

For example, I want to find out if a class has it's own implementation of isEqual: or hash, instead of relying on a super class.

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • Please clarify. Are you talking about looking up something in the documentation? Some sort of runtime check? What? – rmaddy Apr 22 '15 at 21:38
  • @rmaddy He is clearly asking about checking whether a subclass contains custom implementation of a method declared in its superclass. And the question also contains the objective-c runtime tag. – Dominik Hadl Apr 22 '15 at 21:40
  • @DominikHadl Yes,that's exactly what I want. I want to do this in runtime. Assume I don't have documentation for the said class. – cfischer Apr 22 '15 at 21:42
  • Though it is an interesstig question, I'd would consider it code smell if it was used in production code. – vikingosegundo Apr 22 '15 at 21:57
  • @vikingosegundo It's for unit testing code, not production. – cfischer Apr 22 '15 at 22:04

1 Answers1

4

You just need to get a list of the methods, and look for the one you want:

#import <objc/runtime.h>

BOOL hasMethod(Class cls, SEL sel) {
    unsigned int methodCount;
    Method *methods = class_copyMethodList(cls, &methodCount);

    BOOL result = NO;
    for (unsigned int i = 0; i < methodCount; ++i) {
        if (method_getName(methods[i]) == sel) {
            result = YES;
            break;
        }
    }

    free(methods);
    return result;
}

class_copyMethodList only returns methods that are defined directly on the class in question, not superclasses, so that should be what you mean.

If you need class methods, then use class_copyMethodList(object_getClass(cls), &count).

Rob Napier
  • 286,113
  • 34
  • 456
  • 610