HWWY

导航

runtime统计页面数据或者统计按钮的点击次数

一、按钮的点击统计

有的时候我们遇见这样的需求,让我们统计用户点击我们页面的动作的次数给与用户以统计,供以后给客户端推送不同的页面数据,这时候我们就会用到iOS的黑魔法(runtime)。

首先我们不可能修改原始的已经开发完的项目,这时候我们可以采用AOP思想的方式去解决这个问题(只是针对按钮的事件统计,而且不是xib创建的,这里我发现xib创建的不行)。

1、首先新建一个按钮的类别,这里我就不用多讲了。

2、头文件引入

#import <objc/runtime.h>

3、+(void)load;  方法实现我们的加载,为什么在这里写代码了,这与运行时的机制有关系,当你向前

+(void)initialize方法创建可以过早就被覆盖,过迟可能加载不上去,所以我们在选择开始加载运算的时候给他替换。

4、直接上代码:如下

+ (void)load {

    [super load];

    Method fromMethod = class_getInstanceMethod([self class], @selector(sendAction:to:forEvent:));

    Method toMethod = class_getInstanceMethod([self class], @selector(HW_sendAction:to:forEvent:));

    

    BOOL didAddMethod = class_addMethod([self class], @selector(HW_sendAction:to:forEvent:), method_getImplementation(toMethod), method_getTypeEncoding(toMethod));

    

    if (didAddMethod) {

        class_replaceMethod([self class], @selector(HW_sendAction:to:forEvent:), method_getImplementation(fromMethod), method_getTypeEncoding(fromMethod));

    }else{

        method_exchangeImplementations(fromMethod, toMethod);

    }

}

 5、然后实现我们要统计代码的地方,也就是我们用这种岔流给自己预留的埋点。

-(void)HW_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event

{

    //那个页面添加的按钮进行统计

    NSLog(@"这里统计点击事件===%@",target);

}

 

posted on 2018-01-18 17:57  HWWY  阅读(265)  评论(0编辑  收藏  举报