runtime简单的使用解决实际问题(交换方法)

友盟统计中要求在每一个页面的viewWillAppear和viewWillDisappear方法中添加友盟统计的方法:app

若是是项目开始,能够考虑建个BaseViewController,或者用Category也能实现。但是若是是项目已经有了必定规模以后,再提出以上需求,就须要用到更深层次的技术(runtime)了。字体

新建一个viewcontroller的categoryspa

具体代码:指针

#import "UIViewController+UmengAnalysis.h"
#import <objc/message.h>
#import "UMMobClick/MobClick.h"

@implementation UIViewController (UmengAnalysis)
+ (void)load {
    [super load];
// 获取两个方法的IMP(指针)
    Method orgMethod = class_getInstanceMethod([self class], @selector(viewWillAppear:));
    Method swizzledMethod = class_getInstanceMethod([self class], @selector(customViewWillAppear:));
//交换指针
    method_exchangeImplementations(orgMethod, swizzledMethod);
    
    Method orgDisMethod = class_getInstanceMethod([self class], @selector(viewWillDisappear:));
    Method swizzledDisMethod = class_getInstanceMethod([self class], @selector(customViewWillDisAppear:));
    method_exchangeImplementations(orgDisMethod, swizzledDisMethod);
}

- (void)customViewWillAppear:(BOOL)animated {
    [self customViewWillAppear:animated];
    [MobClick beginLogPageView:NSStringFromClass([self class])];
}
- (void)customViewWillDisAppear:(BOOL)animated{
    [self customViewWillDisAppear:animated];
    [MobClick endLogPageView:NSStringFromClass([self class])];
}
@end

UILabel字体大小的问题,相似的新建一个UILabel的categorycode

#import "UILabel+WFFontLabel.h"  
    #import <objc/runtime.h>  

    @implementation UILabel (WFFontLabel)  

    + (void)load {  
        static dispatch_once_t onceToken;  
        dispatch_once(&onceToken, ^{  
            Class class = [self class];  

            // 获取两个方法的IMP(指针)  
            Method originalMethod2 = class_getInstanceMethod(class, @selector(setFont:));  
            Method swizzledMethod2 = class_getInstanceMethod(class, @selector(WFSetFont:));  

            // 交换IMP  
            method_exchangeImplementations(originalMethod2, swizzledMethod2);  

        });  
    }  

    - (void)WFSetFont:(UIFont *)font {  
        UIFont * newFont = [UIFont systemFontOfSize:font.pointSize+10];  
        [self WFSetFont:newFont];  
    }  

    @end

 

load类方法会在每一个页面中被调用,在运行时,viewWillAppearget

方法会被statisticsViewWillAppear替换,viewWillDisappear会被statisticsViewWillDisappear替换,且每一个页面的viewWillAppear、viewWillDisappear方法仍然有效。io

我的感受这是一个很好地能解决多个页面统计的分类。class

相关文章
相关标签/搜索