iOS黑魔法之Method Swizzling

此黑魔法本应属于OC,它是基于Runtime实现的偷天换日大法。

那么什么是Method Swizzling呢?从字面意思来看叫方法协调,大概就是这个意思了。使用此魔法可以替换现有方法为自定义方法,来个偷天换日,偷梁换柱。

使用方法很简单,代码基本为以下框架。但其具有较强的魔力,这是一个方法hook啊。

/**
 *  Method Swizzling
 *  黑魔法之偷天换日
 */
#import "UIViewController+Extension.h"
#import <objc/runtime.h>

@implementation UIViewController (Extension)

// 为了保证一定执行 把代码放到+ (void)load;里
+ (void)load {
    [super load];
    // 线程安全 只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 获取class
        Class class = [self class];
//        Class class = object_getClass((id)self);
        // 封装selector
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(lw_viewWillAppear:);
        // 封装方法
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        // 添加方法
        BOOL methodDidAdd = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if(methodDidAdd) {
            // 替换方法
            class_replaceMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        }else {
            // 交换方法
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

#pragma mark - 自定义的魔法方法
- (void)lw_viewWillAppear:(BOOL)animated {
    [self lw_viewWillAppear:animated];
    NSLog(@"BLack Magic");
}

注意:

1 + (void)load;

2 dispatch_once;

3 [self lw_viewWillAppear:animated]; // 不回死循环 若为[self viewWillAppear:animated];死循环

猜你喜欢

转载自blog.csdn.net/zhaicaixiansheng/article/details/52249042