在目标c中调用super.super上的方法?

P. *_*ami 1 objective-c

所以我所拥有的是一个类层次结构,如下所示:

@interface MyClass : ParentClass

-(void)myMethod
{
    [super myMethod];
    // some specific operation
}

@end

@interface ParentClass : ParentParentClass

-(void)myMethod
{
    [super myMethod];
    // some specific operation
}

@end

@interface ParentParentClass : ParentParentParentClass

-(void)myMethod
{
    [super myMethod];
    // some specific operation
}

@end
Run Code Online (Sandbox Code Playgroud)

现在,让我们说,在MyClass,我想避免调用ParentClassmyMethod,而是要拨打的myMethodParentParentClass.

我该怎么做?

我已经尝试过铸造,super但这不起作用.

Gre*_*reg 5

你应该能够做到这一点:

Method method = class_getInstanceMethod([ParentParentClass class], @selector(myMethod));
IMP imp = method_getImplementation(method);
((void (*)(id, SEL))imp)(self, @selector(myMethod)); // cast the function to the correct signature
Run Code Online (Sandbox Code Playgroud)

您可能需要#import <objc/runtime.h>为此编译.

这将获得该方法在编译时转换为的实际C函数,然后可以调用该函数.当Objective-C编译器编译你的代码时,所有方法都被转换为普通的C函数,它们self作为第一个参数,并且_cmd当前方法的选择器作为第二个参数,然后是所有其他参数,即Objective- C方法需要.class_getInstanceMethod获取给定方法的运行时表示(包括各种元数据),并method_getImplementation从该方法获取普通C函数指针.

如果查看Objective-C运行时头,您将看到该IMP类型被定义为typedef id (*IMP)(void);,因此您需要将其转换为方法实现函数的实际类型,该函数将采用(return_type (*)(id, SEL, method_arguments_in_order))- 函数self和方法选择器它的前两个参数,后跟ObjC方法参数.

因此,一旦有了标准的C函数指针,就可以像调用函数一样调用它.

我不会把这种方法称为hacky,但它肯定是非标准的,因为需要直接使用底层运行时方法来实现你想要的东西.在设计,可靠性和有意义方面,我肯定会认为这是一个更好的解决方案,而不是在调用超类方法的超类中添加桥接方法.