利用Method Swizzling 来抽取重复的操作
by 伍雪颖
重复操作如数据上报,公共特性等等.
1.建立UIViewController的Category
2.代码:
#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.输出
2015-06-16 09:17:59.838 Test[37292:2748514] ana_viewWillAppear
2015-06-16 09:17:59.838 Test[37292:2748514] ViewController: 0x7fb7515291c0>
时间: 2024-10-02 02:29:19