Method Swizzling中的陷阱
来源:互联网 发布:花椒直播mac版 编辑:程序博客网 时间:2024/06/17 12:43
作者:代培
地址:http://blog.csdn.net/dp948080952/article/details/54882811
转载请注明出处
这篇文章不是介绍什么是方法交换,这类文章很多,如果你不知道什么是方法交换可以看这篇文章:Method Swizzling
陷阱
方法交换是很危险的东西,会产生一些未知的错误,最近在使用方法交换时就遇到了这样的问题,在我交换了一个系统方法后,在调用这个方法时会在我交换的方法中循环无法跳出。
最终我找到了问题的关键,那就是这个方法可能不存在!
每次iOS版本的更新都会出现一些新的API,这些API在之前的版本中就不存在,而你在交换一个方法时如果不考虑它是否存在,那就会导致严重的错误。
比如我曾经交换过一个方法:
- (void)openURL:(NSURL*)url options:(NSDictionary<NSString *, id> *)options completionHandler:(void (^ __nullable)(BOOL success))completion
这个方法只在iOS10之后有,别人在使用的时候也会先判断这个方法是否会被响应,但是我们看下面的交换代码会先添加这个方法,如果这个方法不存在,那么本来不会响应就变成了会响应,那么在iOS10之前的系统就会进入这个方法,导致死循环。
Class class = [self class]; Method method1 = class_getInstanceMethod(class, sel1); Method method2 = class_getInstanceMethod(class, sel2); BOOL didAddMethod = class_addMethod(class, sel1, method_getImplementation(method2), method_getTypeEncoding(method2)); if (didAddMethod) { class_replaceMethod(class, sel2, method_getImplementation(method1), method_getTypeEncoding(method1)); } else { method_exchangeImplementations(method1, method2); }
解决方案
解决这个问题也很简单就是交换前做一个判断:
if (![class instancesRespondToSelector:sel1] || ![class instancesRespondToSelector:sel2]) { return ; }
如果不响应这个方法,直接返回。
封装
为了不重复写方法交换的代码,也能减少错误,我们可以将其封装,将其放在NSObject的Category中再合适不过了。
NSObject+DPExtension.h
#import <Foundation/Foundation.h>@interface NSObject (DPExtension)+ (void)intanceMethodExchangeWithOriginSelector:(SEL)sel1 swizzledSelector:(SEL)sel2;@end
NSObject+DPExtension.m
#import "NSObject+DPExtension.h"#import <objc/runtime.h>@implementation NSObject (DPExtension)+ (void)intanceMethodExchangeWithOriginSelector:(SEL)sel1 swizzledSelector:(SEL)sel2 { Class class = [self class]; if (![class instancesRespondToSelector:sel1] || ![class instancesRespondToSelector:sel2]) { return ; } Method method1 = class_getInstanceMethod(class, sel1); Method method2 = class_getInstanceMethod(class, sel2); BOOL didAddMethod = class_addMethod(class, sel1, method_getImplementation(method2), method_getTypeEncoding(method2)); if (didAddMethod) { class_replaceMethod(class, sel2, method_getImplementation(method1), method_getTypeEncoding(method1)); } else { method_exchangeImplementations(method1, method2); }}@end
就是这些^_^
0 0
- Method Swizzling中的陷阱
- Objective-C中的Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- method swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- Method Swizzling
- 1029_魔咒词典
- Docker基本操作
- Lock和synchronized比较详解
- 【Codeforces 735 C Tennis Championship】+ 贪心
- 2017-2-5
- Method Swizzling中的陷阱
- [BZOJ2502]清理雪道(有源汇有上下界的最小流)
- 第十一章粒子系统
- Hash table
- 位运算例题2
- 【Maven】maven初步认识
- HDU-2642-Stars(二维树状数组应用)
- 轻量级框架-butterknife
- Redis 应用案例 - 在问题中不断成长