使用class_getInstanceMethod - 在类层次结构中实现的方法在哪里?

Sea*_*ser 8 objective-c objective-c-runtime ios

是否有可能在类层次结构中找到检索方法的class_getInstanceMethod来源?例如,假设A类实现了myMethod.现在说我已经在A1类中继承了A类.如果我打电话class_getInstanceMethod(ClassA1, myMethod),是否可以判断结果方法是否已在ClassA1中被覆盖或直接来自A1?

我想如果你有权访问ClassA和ClassA1,就可以比较IMP的内存地址,但是我没有直接访问A.

Jac*_*kin 15

您始终可以访问类的超类,因此您可以将其传递给class_getInstanceMethodclass_getMethodImplementation使用相同的超类,SEL并比较IMP地址以查看该子方法是否覆盖了该方法.

如果你想要定义这个方法的根类,这会有点毛茸茸.

无论如何,这里是:

static inline BOOL isInstanceMethodOverridden(Class cls, SEL selector, Class *rootImpClass) {
    IMP selfMethod = class_getMethodImplementation(cls, selector);
    BOOL overridden = NO;
    Class superclass = [cls superclass];
    while(superclass && [superclass superclass]) {
        IMP superMethod = class_getMethodImplementation(superclass, selector);
        if(superMethod && superMethod != selfMethod) {
            overridden = YES;
            if(!rootImpClass) {
                //No need to continue walking hierarchy
                break;
            }
        }

        if(!superMethod && [cls respondsToSelector:selector])) {
            //We're at the root class for this method
            if(rootImpClass) *rootImpClass = cls;
            break;
        }

        cls = superclass;
        superclass = [cls superclass];
    }

    return overridden;
}
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了 (2认同)