跟着产品学技术iOS 知识点

利用category添加友盟页面访问路径统计

2017-03-09  本文已影响378人  fly大梦想家
女神高.jpg

****1.页面路径统计统计****
在需要统计的viewcontroller中导入#import <UMMobClick/MobClick.h>
添加代码

-(void)viewWillAppear:(BOOL)animated{
    [MobClick beginLogPageView:NSStringFromClass([self class])];
}
-(void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:NSStringFromClass([self class])];
}

如果项目页面太多,不想每次都重复如上代码,在利用category在viewcontroller底层添加

#import "UIViewController+Tracking.h"
#import <objc/runtime.h>
#import <UMMobClick/MobClick.h>
@implementation UIViewController (Tracking)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        // When swizzling a class method, use the following:
        // Class class = object_getClass((id)self);
        swizzleMethod(class, @selector(viewWillAppear:), @selector(aop_viewWillAppear:));
        swizzleMethod(class, @selector(viewWillDisappear:), @selector(aop_viewWillDisappear:));
    });
}

void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector)   {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    BOOL didAddMethod =
    class_addMethod(class,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}
-(void)aop_viewWillAppear:(BOOL)animated {
    [self aop_viewWillAppear:animated];
     [MobClick beginLogPageView:NSStringFromClass([self class])];
#ifdef DEBUG
    NSLog(@"👀👀👀👀👀👀👀开启👀👀viewVillAppear:%@",NSStringFromClass([self class]));
#endif

}
-(void)aop_viewWillDisappear:(BOOL)animated {
    [self aop_viewWillDisappear:animated];
   [MobClick endLogPageView:NSStringFromClass([self class])];
#ifdef DEBUG
    NSLog(@"👀👀👀👀👀👀👀关闭👀👀viewDISAppear:%@",NSStringFromClass([self class]));
#endif
}
@end

关于category:
1.1作用:可以在不修改原来类的基础上,为一个类扩展方法。
1.2最主要的用法:给系统自带的类扩展方法。

2.分类中能写点啥?
2.1分类中只能添加“方法”,不能增加成员变量。
2.2分类中可以访问原来类中的成员变量,但是只能访问@protect和@public形式的变量。如果想要访问本类中的私有变量,分类和子类一样,只能通过方法来访问。
2.3如果一定要在分类中添加成员变量,可以通过getter,setter手段进行添加

上一篇下一篇

猜你喜欢

热点阅读