method swizzling注意点

方法交换是OC运行时特征之一,经过方法交换能够hook方法,在实现一些需求时能够达到事半功倍的效果,但使用不慎一样可能致使不可思议的后果。在使用method swizzling前都应该理解如下注意点。objective-c

1.避免交换父类方法

若是当前类未实现被交换的方法而父类实现了的状况下,此时父类的实现会被交换,若此父类的多个继承者都在交换时会致使方法被交换屡次而混乱,同时当调用父类的方法时会由于找不到而发生崩溃。 因此在交换前都应该先尝试为当前类添加被交换的函数的新的实现IMP,若是添加成功则说明类没有实现被交换的方法,则只须要替代分类交换方法的实现为原方法的实现,若是添加失败,则原类中实现了被交换的方法,则能够直接进行交换。shell

这个过程主要涉及如下三个函数:bash

class_addMethod函数

BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
复制代码

给类cls的SEL添加一个实现IMP, 返回YES则代表类cls并未实现此方法,返回NO则代表类已实现了此方法。注意:添加成功与否,彻底由该类自己来决定,与父类有无该方法无关。学习

class_replaceMethod
class_replaceMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, 
                    const char * _Nullable types) 
复制代码

替换类cls的SEL的函数实现为impui

method_exchangeImplementations
method_exchangeImplementations(Method _Nonnull m1, Method _Nonnull m2)
复制代码

交换两个方法的实现m1,m1spa

最终的过程大体以下代码:代理

BOOL didAddMethod = class_addMethod(class,originalSelector,
                                            method_getImplementation(swizzledMethod),
                                            method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {//添加成功:则代表没有实现IMP,将源SEL的IMP替换到交换SEL的IMP
    class_replaceMethod(class,swizzledSelector,
                        method_getImplementation(originalMethod),
                        method_getTypeEncoding(originalMethod));
} else {//添加失败:代表已实现,则能够直接交换实现IMP
    method_exchangeImplementations(originalMethod, swizzledMethod);
}
复制代码

2.交换方法应在+load方法 方法交换应当在调用前完成交换,+load方法发生在运行时初始化过程当中类被加载的时候调用,且每一个类被加载的时候只会调用一次load方法,调用的顺序是父类、类、分类,且他们之间是相互独立的,不会存在覆盖的关系,因此放在+load方法中能够确保在使用时已经完成交换。code

3.交换方法应该放到dispatch_once中执行 在第2点已经写到,+load方法在类被加载的时候调用,且只会调用一次,那为何还须要dispatch_once呢?这是为了防止手动调用+load方法而致使反复的被交换,由于这是存在可能的。继承

4.交换的分类方法应该添加自定义前缀,避免冲突 这个毫无疑问,由于分类的方法会覆盖类中同名的方法,这样会致使没法预估的后果

5.交换的分类方法应调用原实现 不少状况咱们不清楚被交换的的方法具体作了什么内部逻辑,并且不少被交换的方法都是系统封装的方法,因此为了保证其逻辑性都应该在分类的交换方法中去调用原被交换方法,注意:调用时方法交换已经完成,在分类方法中应该调用分类方法自己才正确。

在每次的方法交换时都应该注意以上几点,最终咱们能够将其封装到NSObject的分类中,方便在调用:

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (Swizzling) 

+ (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector
                         swizzledSelector:(SEL)swizzledSelector;
@end
#import "NSObject+Swizzling.h"
@implementation NSObject (Swizzling)

+ (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector{
    Class class = [self class];

    //原有被交换方法
    Method originalMethod = class_getInstanceMethod(class, originalSelector);

    //要交换的分类新方法
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    //避免交换到父类的方法,先尝试添加被交换方法的新实现IMP
    BOOL didAddMethod = class_addMethod(class,originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));

    if (didAddMethod) {//添加成功:则代表没有实现IMP,将源SEL的IMP替换到交换SEL的IMP
        class_replaceMethod(class,swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {//添加失败:代表已实现,则能够直接交换实现IMP
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}
@end
复制代码

开发中,咱们有时会使用runtime进行swizzle方法(若是不知道swizzle请看这里连接)。多数时候咱们会这样写,swizzle第一种写法:

Method originalMethod = class_getInstanceMethod(aClass, originalSel);
    Method swizzleMethod = class_getInstanceMethod(aClass, swizzleSel);
    method_exchangeImplementations(originalMethod, swizzleMethod);
复制代码

或者是下面这种方式,swizzle第二种写法:

Method originalMethod = class_getInstanceMethod(aClass, originalSel);
    Method swizzleMethod = class_getInstanceMethod(aClass, swizzleSel);
    BOOL didAddMethod = class_addMethod(aClass, originalSel, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
    if (didAddMethod) {
        class_replaceMethod(aClass, swizzleSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else{
        method_exchangeImplementations(originalMethod, swizzleMethod);
    }
复制代码

网上资料查找时发现第二种方式网上有称呼为最佳的swizzle方式,具体可见资料(最佳实践相关资料).

上面两种方式具体哪一种好呢,我下不定论,由于在使用过程当中,发现他们各自都有本身的问题(将在下面指出),具体还得看本身需求以为哪一种好,下面将解释这两种方式的一些问题,本文代码见代码地址。

先说说第一种状况(当swizzle一个自身没有实现而父类实现了的方法时)下两种方式比较:

首先咱们创建两个类:father类以及继承fahter类的son类

@interface Father : NSObject
@end
@implementation Father
-(void)work{
    NSLog(@"父亲得赚钱养家????");
}
@end

@interface Son : Father

@end

@implementation Son

@end
复制代码

而后新建Son分类:

@implementation Son (Swizzle)
BOOL simple_Swizzle(Class aClass, SEL originalSel,SEL swizzleSel){

    Method originalMethod = class_getInstanceMethod(aClass, originalSel);
    Method swizzleMethod = class_getInstanceMethod(aClass, swizzleSel);
    method_exchangeImplementations(originalMethod, swizzleMethod);

    return YES;
}
BOOL best_Swizzle(Class aClass, SEL originalSel,SEL swizzleSel){

    Method originalMethod = class_getInstanceMethod(aClass, originalSel);
    Method swizzleMethod = class_getInstanceMethod(aClass, swizzleSel);
    BOOL didAddMethod = class_addMethod(aClass, originalSel, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
    if (didAddMethod) {
        class_replaceMethod(aClass, swizzleSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else{
        method_exchangeImplementations(originalMethod, swizzleMethod);
    }

    return YES;
}
@end
复制代码

这里咱们将第一种方式称为simple_Swizzle,第二种方式为best_Swizzle

状况一:子类里swizzle一个自身没有实现而父类实现了的方法。

咱们在分类中添加一个本身的work方法准备swizzle

@implementation Son (Swizzle)
-(void)son_work{
    [self son_work];
    NSLog(@"son分类里的son_work");
}

@end
复制代码

而后再load方法中进行替换,咱们先使用simple_Swizzle。

+(void)load{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
             simple_Swizzle([self class], NSSelectorFromString(@"work"), @selector(son_work));
    };

}
复制代码

嗯,好了,运行程序后,调用以下代码

Son *son = [Son new];
    [son work];
复制代码

控制台打印以下:

2017-06-18 16:11:20.443302 runtime学习[45823:16276777] 父亲得赚钱养家????
2017-06-18 16:11:20.448797 runtime学习[45823:16276777] son分类里的son_work
复制代码

也许这里你已经发现问题,若是没有咱们继续,再调用下面代码:

Father *aFather = [Father new];
    [aFather work];
复制代码

程序崩溃了,控制台输出:

[Father son_work]: unrecognized selector sent to instance 0x1700162f0' 复制代码

what?(黑人问号?),什么状况!![aFather work]里调用了son_work。

原来,刚刚的simple_Swizzle将子类的son_work的IMP替换给类父类的work方法,致使父类方法work里有[self son_work];而父类并无这样的方法因此over了。

具体为何会替换掉父类的方法,是由于class_getInstanceMethod方法在找方法时会从本身类到父类到根类一直查找下去,一直到根类为止,因此上面在查找work方法时就找到father类里了。这就是simple_Swizzle的一个问题。

如今咱们使用simple_Swizzle来进行替换。

best_Swizzle([self class], NSSelectorFromString(@"work"), @selector(son_work));复制代码 而后

Son *son = [Son new];
    [son work];
复制代码

控制台打印以下:

2017-06-18 16:27:43.491944 runtime学习[45833:16282207] 父亲得赚钱养家????
2017-06-18 16:27:43.493439 runtime学习[45833:16282207] son分类里的son_work
复制代码

没问题,接着:

Father *aFather = [Father new];
    [aFather work];
复制代码

控制台打印以下:

2017-06-18 16:30:39.622756 runtime学习[45836:16282868] 父亲得赚钱养家????
复制代码

能够看到这时父类没有调用son_work。由于best_Swizzle在进行swizzle时会先尝试给本身添加work方法方法实现

BOOL didAddMethod = class_addMethod(aClass, originalSel, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
复制代码

若是son类没有实现work方式时,class_addMethod就会成功添加一个新的属于son本身的work方法,同时将原本要swizzle的方法的实现直接复制进work里,而后再将父类的IMP给swizzle。若是son已经已经实现了则会添加失败,直接进行swizzle具体可见资料(),逻辑为下面代码。

if (didAddMethod) {
        class_replaceMethod(aClass, swizzleSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else{
        method_exchangeImplementations(originalMethod, swizzleMethod);
    }
复制代码

这时simple_Swizzle会有问题,best_Swizzle没有问题。

下面咱们来讲另一种状况(swizzle一个子类到父类到根类都没有实现过的方法):

咱们给son分类添加一个son_Cry方法:

-(void)son_Cry{
    NSLog(@"我是son分类,WZ_Cry方法");
    [self son_Cry];
}
复制代码

同时声明一个没有实现的方法cry;

@interface Son : Father
1
-(void)cry;
@end
复制代码

而后先用simple_Swizzle替换:

simple_Swizzle([self class], @selector(cry), @selector(son_Cry));
复制代码

接着调用cry方法:

Son *son = [Son new];
[son cry];
复制代码

控制台打印:

[Son cry]: unrecognized selector sent to instance 0x170018900' 复制代码

嗯,调用失败,正常由于都没有实现如何swizzle。而后用咱们用回自动添加一个实现的best_Swizzle方式,控制台打印以下:

2017-06-18 16:59:33.815223 runtime学习[45845:16289311] 我是son分类,WZ_Cry方法
2017-06-18 16:59:33.815243 runtime学习[45845:16289311] 我是son分类,WZ_Cry方法
2017-06-18 16:59:33.815319 runtime学习[45845:16289311] 我是son分类,WZ_Cry方法
复制代码

...此处省略无数次上面的log打印

再一次(what?黑人问号?),程序死循环了...

问题出在这两行代码:

//由于cry方法没有实现过,class_getInstanceMethod没法找到该方法,因此originalMethod为nil。

Method originalMethod = class_getInstanceMethod(aClass, originalSel);
复制代码

//当originalMethod为nil时这里class_replaceMethod将不作替换,因此swizzleSel方法里的实现仍是本身原来的实现。

class_replaceMethod(aClass, swizzleSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
复制代码

因此最终致使在下面方法里重复调用本身。

-(void)son_Cry{
    NSLog(@"我是son分类,WZ_Cry方法");
    [self son_Cry];
}
复制代码

这里就是best_Swizzle的一个问题,固然这个问题不多出现,由于咱们通常swizzle时都是swizzle一个已知的方法,因此通常都有方法实现。

可是也不是不会出现这种问题,这里我在一次进行swizzle一个类实现的协议方法时出现了,好比AppDelegate类里的协议,我想在某个代理回调里插入一段本身的逻辑,又不想对已有的项目里直接加入,我想它时能够直接拿到另一个项目也能够直接用的,因此我建了一个分类swizzle协议方法,若是我直接swizzle一个没有实现过的协议方法,就会出现死循环。

具体可见demo

里的解决方法是在originalMethod为nil时,替换后将swizzleSel复制一个不作任何事的空实现,代码以下:

if (!originalMethod)
    {
        class_addMethod(aClass, originalSel, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
        method_setImplementation(swizzleMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));
    }
复制代码

喝口水 总结:

对于simple_Swizzle和best_Swizzle的选择没有具体要求,你们结合本身的场景使用,我通常直接用simple_Swizzle,由于我知道这个方法必定有,因此能简单就粗暴吧。

相关文章
相关标签/搜索