利用runtime 简化友盟统计代码

给UIViewController添加一个分类,实现这个分类

例如,命名为UIViewController+UMengAnalytics

#import "UIViewController+UMengAnalytics.h"
#import 

@implementation UIViewController (UMengAnalytics)

+ (void)load {
    // 系统原本的viewWillApper方法
    Method viewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:));
    // 需要替换成能够输入日志的viewWillAppear
    Method qy_viewWillAppear = class_getInstanceMethod(self, @selector(qy_viewWillAppear:));
    
    // 原本的viewWillDisappear方法
     Method viewWillDisappear = class_getInstanceMethod(self, @selector(viewWillDisappear:));
    //需要替换成能够输入日志的viewWillDisappear
    Method qy_viewWillDisappear = class_getInstanceMethod(self, @selector(qy_viewWillDisappear:));
    
    // 两方法进行交换
    method_exchangeImplementations(viewWillAppear, qy_viewWillAppear);
    method_exchangeImplementations(viewWillDisappear, qy_viewWillDisappear);
}

- (void)qy_viewWillAppear:(BOOL)animated {
    //
    [self qy_viewWillAppear:animated];
    //
    NSString *selfClass = NSStringFromClass([self class]);
    //
    [MobClick beginLogPageView:selfClass];
}

- (void)qy_viewWillDisappear:(BOOL)animated {
    //
    [self qy_viewWillDisappear:animated];
    //
    NSString *selfClass = NSStringFromClass([self class]);
    //
    [MobClick endLogPageView:selfClass];
}

@end

你可能感兴趣的:(利用runtime 简化友盟统计代码)