了解 Objective-C 类是否覆盖了方法


如何在

运行时确定一个类是否覆盖了其超类的方法?

例如,我想找出一个类是否有自己的isEqual:hash实现,而不是依赖于超类。

你只需要获取一个方法列表,然后寻找你想要的方法:

#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只返回直接在相关类上定义的方法,而不是超类,所以这应该是你的意思。

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

最新更新