Shadow Of Shadow Of - 3 months ago 11
Objective-C Question

Is it possible to go deeper than nearest superclass (i.e. super.super)?

Assume that I want to skip one level in call

super.viewDidLoad()
, for example. So I wish to be able to do something like this:

override func viewDidLoad() {
super.super.viewDidLoad()
}


or

-(void)viewDidLoad {
[[super super] viewDidLoad];
}


This code will not compile. Is this possible by some other solution?

Avi Avi
Answer

For expository purposes only, the following code does as requested. It only fails to crash when compiled without ARC, which means it has a bug in it. It does no error checking.

Never use this code unless you are playing around and trying to learn.

@import Foundation;
#import <objc/runtime.h>
#import <objc/message.h>

@interface M : NSObject

- (void)print;

@end

@implementation M

- (void)print { NSLog(@"M"); }

@end

@interface N : M
@end

@implementation N

- (void)print { NSLog(@"N"); }

@end

@interface O : N
@end

@implementation O

- (void)print {
    Class mysupersuper = [[self superclass] superclass];
    Method supersuperMethod = class_getInstanceMethod(mysupersuper, _cmd);

    method_invoke(self, supersuperMethod);
}

@end

int main(int argc, char **argv)
{
    O *o = O.new;

    [o print];

    return 0;
}

I compiled it using the command: clang -framework Foundation -fno-objc-arc -fmodules test.m.

Comments