码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-16 11:12:19      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:category

利用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>

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

标签:category

原文地址:http://blog.csdn.net/rainlesvio/article/details/46514193

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!