Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if an Objective-C class overrides a method [duplicate]

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.

like image 285
cfischer Avatar asked Apr 22 '15 21:04

cfischer


1 Answers

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).

like image 99
Rob Napier Avatar answered Nov 16 '22 05:11

Rob Napier