在 iOS 上是否有任何优雅的方法可以将挂钩方法恢复为原始实现?

Is there any graceful way could revert the hooked method to original implementation on iOS?

使用 CydiaSubstrate 我们可以很容易地 hook 下面的方法,但我想知道如何卸载 hooking 并将实现恢复为原始方法?谢谢!

static IMP original_UIView_setFrame_;
void replaced_UIView_setFrame_(UIView* self, SEL _cmd, CGRect frame) {  // Note the implicit self and _cmd parameters are needed explicitly here.
  CGRect originalFrame = self.frame;
  NSLog("Changing frame of %p from %@ to %@", self, NSStringFromCGRect(originalFrame), NSStringFromCGRect(frame));
  original_UIView_setFrame_(self, _cmd, frame);    // Remember to pass self and _cmd.
}
...
MSHookMessageEx([UIView class], @selector(setFrame:), (IMP)replaced_UIView_setFrame_, (IMP *)&original_UIView_setFrame_);

你只需要再次交换实现,即再次调用以下代码:

MSHookMessageEx([UIView class], @selector(setFrame:), (IMP)replaced_UIView_setFrame_, (IMP *)&original_UIView_setFrame_);

当你交换实现时,你就是在交换它们,所以通过再次交换它们,你又回到了原来的状态。