Method Swizzling is used to extract repeated operations. methodswizzling
Use Method Swizzling to extract repeated operations
By Wu xueying
Repeated operations, such as data reporting and public features.
1. Create a Category for UIViewController
2. Code:
#import "UIViewController+Analytics.h"#import <objc/runtime.h>@implementation UIViewController (Analytics)+ (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Class class = [self class]; SEL originalSelector = @selector(viewWillAppear:); SEL swizzledSelector = @selector(ana_viewWillAppear:); Method originalMethod = class_getInstanceMethod(class, originalSelector); Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (success) { class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } });}- (void)ana_viewWillAppear:(BOOL)animated { [self ana_viewWillAppear:animated]; NSLog(@"ana_viewWillAppear"); NSLog(@"%@",self); MTA_Report(); [self hideNavigationShadowLine];}@end
3. Output
09:17:59. 838 Test [37292: 2748514] ana_viewWillAppear
09:17:59. 838 Test [37292: 2748514] ViewController: 0x7fb7515291c0>