Copy a method IMP for multiple method swizzles

最后都变了- 提交于 2019-12-05 17:58:02

That common method-swizzling pattern only works when you want to intercept one method with one other. In your case you are basically moving the implementation for catchAll: around instead of inserting it everywhere.

To properly to this you'd have to use:

IMP imp = method_getImplementation(newMethod);
method_setImplementation(origMethod, imp);

This leaves you with one problem though: how to forward to the original implementation?
That is what the original pattern used exchangeImplementations for.

In your case you could:

  • keep a table of the original IMPs around or
  • rename the original methods with some common prefix, so you can build a call to them from catchAll:

Note that you can only handle methods of the same arity when you want to forward everything through the same method.

You can capture original IMP with block, get block's IMP and set it as implementation of method.

Method method = class_getInstanceMethod(class, setterSelector);
SEL selector = method_getName(method);
IMP originalImp = method_getImplementation(method);

id(^block)(id self, id arg) = ^id(id self, id arg) {
    return ((id(*)(id, SEL, id))originalImp)(self, selector, arg);
};

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