NSObject+RQSafe.m 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. //
  2. // NSObject+RQSafe.m
  3. // jiaPei
  4. //
  5. // Created by 张嵘 on 2019/4/2.
  6. // Copyright © 2019 JCZ. All rights reserved.
  7. //
  8. #import "NSObject+RQSafe.h"
  9. @implementation NSObject (RQSafe)
  10. + (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector{
  11. Class class = [self class];
  12. //原有方法
  13. Method originalMethod = class_getInstanceMethod(class, originalSelector);
  14. //替换原有方法的新方法
  15. Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
  16. //先尝试給源SEL添加IMP,这里是为了避免源SEL没有实现IMP的情况
  17. BOOL didAddMethod = class_addMethod(class,originalSelector,
  18. method_getImplementation(swizzledMethod),
  19. method_getTypeEncoding(swizzledMethod));
  20. if (didAddMethod) {//添加成功:说明源SEL没有实现IMP,将源SEL的IMP替换到交换SEL的IMP
  21. class_replaceMethod(class,swizzledSelector,
  22. method_getImplementation(originalMethod),
  23. method_getTypeEncoding(originalMethod));
  24. } else {//添加失败:说明源SEL已经有IMP,直接将两个SEL的IMP交换即可
  25. method_exchangeImplementations(originalMethod, swizzledMethod);
  26. }
  27. }
  28. @end