今天在群里看到有人说在viewWillAppear方法里添加埋点的问题
为了降低代码耦合度,我就觉得可以用runtime的方法交换来实现
controller里的代码
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSLog(@"2222222222222"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
category里的代码
#import "UIViewController+NewApear.h" #import <objc/message.h> @implementation UIViewController (NewApear) -(void)newAppear:(BOOL)animated{ [self newAppear:animated]; NSLog(@"my code"); } +(void)load{ //交换方法 NSLog(@"333"); SEL originalSelector = @selector(viewWillAppear:); SEL swizzledSelector = @selector(newAppear:); Class class = [self class]; Method originalMethod = class_getInstanceMethod(class, originalSelector); Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (didAddMethod) { class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } } @end
这里的代码是没问题的,但是我刚开始写demo的时候,在使用viewWillAppear的时候没有写
[super viewWillAppear:animated];
导致自定义的方法不执行,所以这个super一定要调用