笔记-method-swizzling~那些年,一块儿遇过的坑

什么是method-swizzling?

method-swizzling俗称黑魔法,在前几篇文章中说过,在OC中调用一个方法,其实就是向一个对象发送消息,而查找消息的惟一依据是selector的名字,经过名字查找到IMP。利用OC的动态特性,能够实如今运行时偷换selector对应的方法实现,达到方法实现交换的效果。程序员

能够经过下图去理解 数组

在什么地方进行方法交换,为何?

+load方法里,缘由有三:(后面文章里会具体分析这个+load方法)bash

  • 执行比较早,在main函数以前调用
  • 自动执行,不须要手动执行
  • 惟一性,不用担忧被子类覆盖

坑一:找不到真正的方法归属

数组越界,是开发中最多见的一个错误,看下面代码函数

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = @[@"AA",@"BB",@"CC",@"DD"];
    NSLog(@"%@",self.dataArray[4]);
}
复制代码

这段代码执行结果,相信我不用说了,奔溃,以下图(其实都不用给图的。。。) 优化

其实能够利用这个黑魔法,去规避App的奔溃,同时能够打印出奔溃的类的所在代码的行数,下面就用这个机制,阻止它的奔溃,代码以下ui

@implementation ZBRuntimeTool
+ (void)zb_methodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL {
    if (!cls) NSLog(@"传入的交换类不能为空");
    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    method_exchangeImplementations(oriMethod, swiMethod);
}
@end

// 分类中
@implementation NSArray (ZB)
+ (void)load {
    [ZBRuntimeTool zb_methodSwizzlingWithClass:self oriSEL:@selector(objectAtIndex:) swizzledSEL:@selector(zb_objectAtIndex:)];
}

- (id)zb_objectAtIndex:(NSUInteger)index {
    if (index > self.count-1) {
        NSLog(@"取值越界了,请记录 : %lu > %lu",(unsigned long)index,self.count-1);
        return nil;
    }
    return [self zb_objectAtIndex:index];
}
@end
复制代码

搞定,是否是感受很简单,编译运行看打印效果,一顿操做猛如虎,结果发现运行仍是奔溃😅,其实这就是在上面我为何要给出奔溃的截图,细心的小伙伴可能已经知道来缘由,上面代码的错误有两处:
第一就是方法的归属,咱们写的是self,指的是NSArray,可是经过它报错的结果能够知道应该是__NSArrayI,它是一个族类,这个必定要分清;
第二是咱们交换的方法错误,一样仍是能够经过上面的截图能够看得出来,咱们应该交换objectAtIndexedSubscript:方法spa

最终代码以下:设计

@implementation NSArray (ZB)
+ (void)load {
    [ZBRuntimeTool zb_methodSwizzlingWithClass:objc_getClass("__NSArrayI") oriSEL:@selector(objectAtIndexedSubscript:) swizzledSEL:@selector(zb_objectAtIndexedSubscript:)];
}

- (id)zb_objectAtIndexedSubscript:(NSUInteger)index {
    if (index > self.count-1) {
        NSLog(@"取值越界了,请记录 : %lu > %lu",(unsigned long)index,self.count-1);
        return nil;
    }
    return [self zb_objectAtIndexedSubscript:index];
}
@end
复制代码

这段代码能够解决上面所遇到的问题,可是很明显,这样的代码漏洞百出,一个优秀的程序员不该该写到这里就中止的,后面篇章中,会持续优化它。3d

坑二:可能会主动调用load方法

还能够拿上面的例子来讲事,下面代码中的调用code

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = @[@"AA",@"BB",@"CC",@"DD"];
    [NSArray load];
    NSLog(@"%@",self.dataArray[4]);
}
复制代码

运行结果和上面的结果一摸同样,直接奔溃,并且报错信息都是同样的,应该可以想到缘由,两次的交换,使得它们都指向了原来的IMP,因此为了防止这种屡次调用的状况,咱们能够经过让它只运行一次来解决这个问题,代码以下:

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [ZBRuntimeTool zb_methodSwizzlingWithClass:objc_getClass("__NSArrayI") oriSEL:@selector(objectAtIndexedSubscript:) swizzledSEL:@selector(zb_objectAtIndexedSubscript:)];
    });
}
复制代码

对的,没有错,利用单例的方式去解决上面的这个问题。

坑三:子类没有实现父类的方法,子类交换了父类的方法

下看看下面代码

// Person类
@interface ZBPerson : NSObject
- (void)personInstanceMethod;
@end

@implementation ZBPerson
- (void)personInstanceMethod {
    NSLog(@"person对象方法:%s",__func__);
}
@end

// Student类
@interface ZBStudent : ZBPerson
- (void)helloWorld;
+ (void)helloWorld1;
                // 没有实现父类ZBPerson的方法
@end

// 调用
- (void)viewDidLoad {
    [super viewDidLoad];
    ZBStudent *s = [[ZBStudent alloc] init];
    [s personInstanceMethod];

    ZBPerson *p = [[ZBPerson alloc] init];
    [p personInstanceMethod];
}
复制代码

上面代码中有两个类,ZBPersonZBStudent,其中ZBStudent是继承于ZBPerson,也没有实现ZBPerson中的方法personInstanceMethod

下面进行方法交换

@implementation ZBStudent (ZB)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [ZBRuntimeTool zb_betterMethodSwizzlingWithClass:self oriSEL:@selector(personInstanceMethod) swizzledSEL:@selector(zb_studentInstanceMethod)];
    });
}

- (void)zb_studentInstanceMethod{
    NSLog(@"ZBStudent分类添加的zb对象方法:%s",__func__);
    [self zb_studentInstanceMethod];
}
@end
复制代码

若是ZBRuntimeTool类里面的方法交换仍是和上面写的同样的话,运行结果确定是奔溃的,这里就不过多描述这个错误,下面是优化过的代码

+ (void)zb_betterMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    if (!cls) NSLog(@"传入的交换类不能为空");
    
    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    // 通常交换方法: 交换本身有的方法 -- 走下面 由于本身有意味添加方法失败
    // 交换本身没有实现的方法:
    //   首先第一步:会先尝试给本身添加要交换的方法 :personInstanceMethod (SEL) -> swiMethod(IMP)
    //   而后再将父类的IMP给swizzle  personInstanceMethod(imp) -> swizzledSEL 
    //oriSEL:personInstanceMethod
    BOOL didAddMethod = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
    if (didAddMethod) {
        class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
    }else{
        method_exchangeImplementations(oriMethod, swiMethod);
    }
}
复制代码

这段代码比以前的多了几步操做,第一步会先尝试给本身添加要交换的方法,若是添加成功,说明本类中没有实现这个方法,那么就直接添加一个swiMethodIMP,而后经过方法class_replaceMethod进行替换;若是添加失败,说明类中存在了这个方法的IMP,那么能够直接利用method_exchangeImplementations方法进行交换。

坑四:交换根本没有实现的方法

顾名思义就是说交换的方法,不只本类未实现,其父类中也没有实现,一样能够拿上面例子提及,ZBStudent类中的方法helloWorld,在其父类以及本类中,都没有实现。

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [ZBRuntimeTool zb_betterMethodSwizzlingWithClass:self oriSEL:@selector(helloWorld) swizzledSEL:@selector(zb_studentInstanceMethod)];
    });
}

- (void)zb_studentInstanceMethod{
    NSLog(@"ZBStudent分类添加的zb对象方法:%s",__func__);
    [self zb_studentInstanceMethod];
}
复制代码

运行结果以下:

能够看出,进入了递归。

思考一下,这里为何会进入递归的死循环呢?

分析Method-Swizzling的原理就是进行消息IMP的交换,执行上面load方法后,先会把方法helloWorldIMP指向zb_studentInstanceMethod(IMP),而后把zb_studentInstanceMethod方法的IMP指向helloWorld(IMP)。注意了,这里的helloWorld(IMP)为空,意思是方法zb_studentInstanceMethodIMP并无改变成功,仍是指向了本身的IMP,和方法helloWorld同样。因此会一直调用方法zb_studentInstanceMethod,进入了死循环的递归。

优化代码:

+ (void)zb_bestMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    if (!cls) NSLog(@"传入的交换类不能为空");
    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    if (!oriMethod) {
        class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
        // IMP指向了一个空的block方法(空IMP)
        method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));
    }

    BOOL didAddMethod = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
    if (didAddMethod) {
        class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
    }else{
        method_exchangeImplementations(oriMethod, swiMethod);
    }
}
复制代码

运行结果:

牛逼哦 老铁们!!!

坑五:类方法--类方法存在元类中

其实类方法的method-swizzling和对象方法基本相似,可是有一个很大的区别,就是类方法存在元类中,代码以下

@implementation ZBStudent (ZB)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [ZBRuntimeTool zb_bestMethodSwizzlingWithClass:self oriSEL:@selector(helloWorld1) swizzledSEL:@selector(zb_studentInstanceMethod1)];
    });
}

+ (void)zb_studentInstanceMethod1{
    NSLog(@"ZBStudent分类添加的zb对象方法:%s",__func__);
    [[self class] zb_studentInstanceMethod1];
}
@end

+ (void)zb_bestMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    if (!cls) NSLog(@"传入的交换类不能为空");
    Method swiCLassMethod = class_getClassMethod([cls class], swizzledSEL);
    Method oriClassMethod = class_getClassMethod([cls class], oriSEL);
    if (!oriClassMethod) {
        class_addMethod(object_getClass([cls class]), oriSEL, method_getImplementation(swiCLassMethod), method_getTypeEncoding(swiCLassMethod));
        method_setImplementation(swiCLassMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));
    }

    BOOL didAddMethod = class_addMethod(object_getClass([cls class]), oriSEL, method_getImplementation(swiCLassMethod), method_getTypeEncoding(swiCLassMethod));
    if (didAddMethod) {
        class_replaceMethod(object_getClass([cls class]), swizzledSEL, method_getImplementation(oriClassMethod), method_getTypeEncoding(oriClassMethod));
    }else {
        method_exchangeImplementations(oriClassMethod, swiCLassMethod);
    }
}
复制代码

代码执行结果:

嗯,上面代码中多处用到 object_getClass([cls class]),实际上这个就是元类,关于类方法的一些 IMP的交换都是在元类中进行的,由于 类方法存在元类中

以上总结了一些关于Method-Swizzling的坑,固然确定不止这几个。在平常开发中仍是慎用,不过真的很强大。上面的几种模式下的代码,值得细细阅读,能够增长对Method-Swizzling的理解,若有错误,但愿指出,谢谢

若是对此很感兴趣,能够了解一下AOP切面设计的源码实现

相关文章
相关标签/搜索