找出Objective-C类是否覆盖方法

cfi*_*her 7 cocoa introspection objective-c objective-c-runtime

如何在运行时找出类是否覆盖其超类的方法?

例如,我想找出一个类有它自己的执行isEqual:hash,而不是依赖于一个超类.

Rob*_*ier 4

您只需要获取方法列表,然后查找您想要的方法:

#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;
}
Run Code Online (Sandbox Code Playgroud)

class_copyMethodList只返回直接在相关类上定义的方法,而不是超类,所以这应该就是你的意思。

如果您需要类方法,请使用class_copyMethodList(object_getClass(cls), &count).