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

什么是method-swizzling?

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

可以通过下图去理解

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

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

  • 执行比较早,在main函数之前调用
  • 自动执行,不需要手动执行
  • 唯一性,不用担心被子类覆盖

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

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

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

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

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

@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:方法

最终代码如下:

@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
复制代码

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

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

还可以拿上面的例子来说事,下面代码中的调用

- (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切面设计的源码实现

转载于:https://juejin.im/post/5ca36a86e51d4514c01636ca

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值