If I override a class method, is there a way I can call the original method (the one that was overridden)?

前端 未结 3 1857
清酒与你
清酒与你 2021-01-03 13:53

In Objective-C, if I override a class method using a category, is there a way I can call the original method (the one that was overridden)?

相关标签:
3条回答
  • 2021-01-03 14:48

    http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCategories.html

    Doesn't look like it is possible.

    When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that already existed in the category's class, there is no way to invoke the original implementation.

    What this is saying to me is that if you override a method on a subclass via a category, you can call [super methodName] as you would normally, but if you override the base class method directly, you can't invoke the original.

    0 讨论(0)
  • 2021-01-03 14:51

    If you dynamically provide the category override (see resolveInstanceMethod:), you can cache the previous method selector beforehand, and call that.

    0 讨论(0)
  • 2021-01-03 14:55

    I present you with three icky ways to do this in +(void)load. In every case, name your method MyCategory_method or so.

    • class_getMethodImplementation() and class_replaceMethod(). Store the old IMP, and call it directly. You need to get the method's type encoding. Note that you can just use a normal C function too...
    • class_getInstanceMethod(), method_getImplementation(), method_setImplementation(). As above, but you don't need to get the method's type encoding.
    • class_getInstanceMethod() on both methods, and then method_exchangeImplementations(). Call MyCategory_method to get the original implementation. This is the easiest way to do it.

    Sometimes, it's the only reasonably easy way to make it do what you want...

    EDIT: And only do this if you know what you're doing!

    0 讨论(0)
提交回复
热议问题