代码之家  ›  专栏  ›  技术社区  ›  executor21

如何从其他地方调用Objective-C对象超类的方法?

  •  16
  • executor21  · 技术社区  · 16 年前

    如果要实现子类,则可以在实现中显式调用超类的方法,即使您已经重写了该方法,也就是说:

    [self overriddenMethod]; //calls the subclass's method
    [super overriddenMethod]; //calls the superclass's method
    

    如果您想从子类实现之外的某个地方调用超类的方法,例如:

    [[object super] overriddenMethod]; //crashes
    

    这是可能的吗?而且,通过扩展,是否可以在实现中提升一个以上的级别,即:

    [[super super] overriddenMethod]; //will this work?
    
    2 回复  |  直到 16 年前
        1
  •  21
  •   Jens Ayton    16 年前

    一个更令人愉快的选择(用于调试)是添加一个Category方法,该方法为您提供:

    - (void) callSuperMethod { [super overriddenMethod]; }
    

    事实上,没有比这更方便的方法了,这在很大程度上是由设计造成的。

        2
  •  13
  •   Nicholas Riley    16 年前

    你可以发送 [[[object class] superclass] methodForSelector: ...] 如果需要,直接通过IMP指针调用…但是,如果您这样做,那么您的应用程序的设计可能有很大的问题。