我正在处理方法 swizzling,并想在执行method_exchangeImplementations. 我为此设置了两个项目。
第一个项目是应用程序的主项目。该项目包括应用程序的所有逻辑。请注意,originalMethodName在视图加载时调用。
@implementation ViewController
- (void)originalMethodName
{
NSLog(@"REAL %s", __func__);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"REAL %s", __func__);
[self originalMethodName];
}
@end
Run Code Online (Sandbox Code Playgroud)
第二个项目仅包含用于 swizzling 的代码。我有一个方法swizzle_originalMethodName,其中包含我想注入到主应用程序的originalMethodName代码,并调用函数。
@implementation swizzle_ViewController
- (void)swizzle_originalMethodName
{
NSLog(@"FAKE %s", __func__);
}
__attribute__((constructor)) static void initializer(void)
{
NSLog(@"FAKE %s", __func__);
Class c1 = objc_getClass("ViewController");
Class c2 = [swizzle_ViewController class];
Method m1 = class_getInstanceMethod(c1, @selector(originalMethodName));
Method m2 = class_getInstanceMethod(c2, @selector(swizzle_originalMethodName));
method_exchangeImplementations(m1, m2);
}
@end
Run Code Online (Sandbox Code Playgroud)
swizzle 工作得很好(如下面的输出所示),但现在我希望能够originalMethodName从 …