什么是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:personInstanceMethodBOOL 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

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

  1. runtime实践之Method Swizzling

    利用 Objective-C 的 Runtime 特性,我们可以给语言做扩展,帮助解决项目开发中的一些设计和技术问题.这一篇,我们来探索一些利用 Objective-C Runtime 的黑色技巧.这 ...

  2. Method Swizzling的各种姿势

    因为Objective-C的runtime机制, Method Swizzling这个黑魔法解决了我们实际开发中诸多常规手段所无法解决的问题, 比如代码的插桩,Hook,Patch等等. 我们首先看看 ...

  3. 关于Swift4.0 Method Swizzling(iOS的hook机制)使用

    2019独角兽企业重金招聘Python工程师标准>>> 关于Method Swizzling 原理什么的有很多帖子讲述的已经很清楚这里不再赘述, 这里仅仅处理Method Swizz ...

  4. 【原】iOS动态性(三) Method Swizzling以及AOP编程:在运行时进行代码注入

    概述 今天我们主要讨论iOS runtime中的一种黑色技术,称为Method Swizzling.字面上理解Method Swizzling可能比较晦涩难懂,毕竟不是中文,不过你可以理解为" ...

  5. Method Swizzling 为什么要先调用 class_addMethod?

    先上个 Swift 中的 demo:Method Swizzling Swift 中的实现 其实 Swift 中实现原理和 OC 基本一致,只是苹果爸爸不再允许在 Swift 中使用+load()和+ ...

  6. Objective-C Runtime 运行时之四:Method Swizzling

    理解Method Swizzling是学习runtime机制的一个很好的机会.在此不多做整理,仅翻译由Mattt Thompson发表于nshipster的Method Swizzling一文. Me ...

  7. Objective-C Runtime (三):Method Swizzling(方法替换)

    Objective-C Runtime (三):Method Swizzling(方法替换) Method Swizzling是一种改变改变一个'selector'的实际实现的技术.通过这一技术,我们 ...

  8. Objective-C的hook方案(一): Method Swizzling

    在没有一个类的实现源码的情况下,想改变其中一个方法的实现,除了继承它重写.和借助类别重名方法暴力抢先之外,还有更加灵活的方法吗?在Objective-C编程中,如何实现hook呢?标题有点大,计划分几 ...

  9. iOS 开发:『Runtime』详解(二)Method Swizzling

    本文用来介绍 iOS 开发中『Runtime』中的黑魔法Method Swizzling. 通过本文,您将了解到: Method Swizzling(动态方法交换)简介 Method Swizzlin ...

  10. iOS总结-Runtime篇之黑魔法Method Swizzling的滥用会有危险吗

    参考https://www.jianshu.com/p/19c5736c5d9a, http://blog.sina.com.cn/s/blog_a343f32b0101en4o.html runti ...

最新文章

  1. python每日一类(3):os和sys
  2. C语言经典例71-编写函数输出结构体数据
  3. [architecture]-ARMV7的模式切换总结
  4. 1025 反转链表 (25分)(最详细最简便)(套路模板)
  5. linux 文件按时间 函数,[Linux文件属性]使用utime函数操作文件的时间参数
  6. LeetCode 2080. 区间内查询数字的频率(哈希+二分查找)
  7. jsencrypt vue使用_在Vue项目中使用jsencrypt.js对数据进行加密传输
  8. Intel Core Enhanced Core架构/微架构/流水线 (12) - 数据预取
  9. C# dataGridView用法
  10. JQuery插件iScroll实现下拉刷新,滚动翻页特效
  11. 微信小程序问答论坛+后台管理系统
  12. android阿里图标库,Android Stdio调用阿里图标库
  13. Bugku之网站被黑
  14. 速度与压缩比如何兼得?压缩算法在构建部署中的优化
  15. Flutter仿网易云音乐 ---基础准备
  16. 合同和协议的区别_合同的内容包括哪些,合同和协议的区别
  17. 互联网的996与华为的惊世骇俗
  18. (私人收藏)2019WER积木教育机器人赛(普及赛)解决方案-(全套)采集深度学习样本
  19. Apache ab 测试报告详解
  20. 仙之侠道2玖章各个任务详情_仙之侠道2玖章给Z武器的任务 | 手游网游页游攻略大全...

热门文章

  1. 写在2017年的总结
  2. django-xadmin定制之分页显示数量
  3. 权限管理系统之字典(代码)管理
  4. iOS-自定义导航栏后侧滑返回功能失效
  5. ANDROID常用的命令(转载,后续自己完善)
  6. delphi中exit,abort,break,continue 的区别
  7. 情人节,请带走我给您的祝福
  8. android getpost代码
  9. Git 和 SVN之间的五个基本区别
  10. 第一个Activity传到第二个Activity