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

可紊 提交于 2019-12-22 04:47:07

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/29809308/find-out-if-an-objective-c-class-overrides-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!