需求:项目完成后,boss要统计所有界面的停留时间。
使用runtime能方便处理
思路:所有控制器继承自UIViewController,给UIViewController写个分类,重写load方法,用runtime的method_exchangeImplementations交换系统生命周期方法。
@implementation UIViewController (zxh)
+(void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_viewDidAppear:"));
Method m2 = class_getInstanceMethod(self, NSSelectorFromString(@"viewDidAppear:"));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_viewDidLoad"));
m2 = class_getInstanceMethod(self, NSSelectorFromString(@"viewDidLoad"));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_viewWillAppear:"));
m2 = class_getInstanceMethod(self, NSSelectorFromString(@"viewWillAppear:"));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_viewWillDisappear:"));
m2 = class_getInstanceMethod(self, NSSelectorFromString(@"viewWillDisappear:"));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_viewDidDisappear:"));
m2 = class_getInstanceMethod(self, NSSelectorFromString(@"viewDidDisappear:"));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_dealloc"));
m2 = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
method_exchangeImplementations(m1, m2);
m1 = class_getInstanceMethod(self, NSSelectorFromString(@"zxh_didReceiveMemoryWarning"));
m2 = class_getInstanceMethod(self, NSSelectorFromString(@"didReceiveMemoryWarning"));
method_exchangeImplementations(m1, m2);
});
}
static int loadTime = 0;
-(void)zxh_viewDidAppear:(BOOL)animated{
NSLog(@"%@<======zxh_viewDidAppear",[self class]);
loadTime = [NSDate timeIntervalSinceReferenceDate];
[self zxh_viewDidAppear:animated];
}
-(void)zxh_viewDidLoad{
NSLog(@"%@+++++++++zxh_viewDidLoad",[self class]);
[self zxh_viewDidLoad];
}
-(void)zxh_viewWillAppear:(BOOL)animated{
NSLog(@"%@======>zxh_viewWillAppear",[self class]);
[self zxh_viewWillAppear:animated];
}
-(void)zxh_viewWillDisappear:(BOOL)animated{
NSLog(@"%@<======zxh_viewWillDisappear",[self class]);
NSLog(@"%@ 时间: %f",[self class], [NSDate timeIntervalSinceReferenceDate] - loadTime);
[self zxh_viewWillDisappear:animated];
}
-(void)zxh_viewDidDisappear:(BOOL)animated{
NSLog(@"%@-------zxh_viewDidDisappear",[self class]);
[self zxh_viewDidDisappear:animated];
}
-(void)zxh_dealloc{
NSLog(@"%@**********zxh_dealloc", [self class]);
[self zxh_dealloc];
}
-(void)zxh_didReceiveMemoryWarning{
NSLog(@"%@**********内存警告!!!!", [self class]);
[self zxh_didReceiveMemoryWarning];
}
网友评论