利用Method Swizzling 来抽取重复的操作

来源:互联网 发布:linux系统网银吗 编辑:程序博客网 时间:2024/05/16 07:11

利用Method Swizzling 来抽取重复的操作

by 伍雪颖

重复操作如数据上报,公共特性等等.

1.建立UIViewController的Category
这里写图片描述
这里写图片描述

2.代码:

#import "UIViewController+Analytics.h"#import <objc/runtime.h>@implementation UIViewController (Analytics)+ (void)load {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        Class class = [self class];        SEL originalSelector = @selector(viewWillAppear:);        SEL swizzledSelector = @selector(ana_viewWillAppear:);        Method originalMethod = class_getInstanceMethod(class, originalSelector);        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);        BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));        if (success) {            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));        } else {            method_exchangeImplementations(originalMethod, swizzledMethod);        }    });}- (void)ana_viewWillAppear:(BOOL)animated {    [self ana_viewWillAppear:animated];    NSLog(@"ana_viewWillAppear");    NSLog(@"%@",self);    MTA_Report();    [self hideNavigationShadowLine];}@end

3.输出
2015-06-16 09:17:59.838 Test[37292:2748514] ana_viewWillAppear
2015-06-16 09:17:59.838 Test[37292:2748514] ViewController: 0x7fb7515291c0>

1 1
原创粉丝点击