Call super without “super” keyword

拜拜、爱过 提交于 2019-12-05 21:50:25

You will have to

  1. get the receivers class (e.g. with object_getClass(rcv))
  2. then get the super class of it (with class_getSuperclass(class))
  3. then get the implementation of it (with class_getMethodImplementation(superclass, sel))
  4. then call the imp.

done

Stop at any step if you got nil or NULL.

Oh, and all this seems silly. But I assume that the question just lacks of context to see the motivation for such a hack.

[Update]

An explanation for future readers:

The super keyword is resolved at compile time. Therefore it does not the intended thing when changing methods at runtime. A method which is intended to be injected in some object (and its class hierarchy) at runtime has to do super calls via runtime as outlined above.

Assuming that the runtime changes you're making involve modifying the superclass, you'll have to do something like this:

@implementation AttackerClass 
-(void) drawRect:(CGRect)rect
{
    if( [super respondsToSelector:@selector(drawRect:)] )
    {
        [super drawRect:rect];
    }
    [self setupPrettyBackground];
}
@end

This will check if the superclass "knows about" drawRect:, and doesn't call it in the case that super has no drawRect: selector.

Hence, when the superclass is NSObject the drawRect: message will not be sent. When you change it to UIView at runtime (whatever your reason for that is), the message can safely be sent.

One approach is to use objc_msgSendSuper. Your method -[AttackerClass drawRect:] will have the following implementation:

- (void)drawRect:(CGRect)rect {
  struct objc_super superTarget;
  superTarget.receiver = self;
  superTarget.class = object_getClass(self);
  objc_msgSendSuper(&superTarget, @selector(drawRect:), rect);
  [self setupPrettyBackground];
}

but why do you need to call draw rect method for superclass NSObject, when NSObject hasn't got that method? just don't do it... call it just in VictimClass drawrect

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