NSObject+Catrgory.m 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. //
  2. // NSObject+Catrgory.m
  3. // 乐销
  4. //
  5. // Created by 隋林栋 on 2017/2/17.
  6. // Copyright © 2017年 ping. All rights reserved.
  7. //
  8. #import "NSObject+Catrgory.h"
  9. #import <objc/runtime.h>
  10. @implementation NSObject (Catrgory)
  11. + (void)SwizzlingMethod:(NSString *)systemMethodString systemClassString:(NSString *)systemClassString toSafeMethodString:(NSString *)safeMethodString targetClassString:(NSString *)targetClassString{
  12. //获取系统方法IMP
  13. Method sysMethod = class_getInstanceMethod(NSClassFromString(systemClassString), NSSelectorFromString(systemMethodString));
  14. //自定义方法的IMP
  15. Method safeMethod = class_getInstanceMethod(NSClassFromString(targetClassString), NSSelectorFromString(safeMethodString));
  16. //IMP相互交换,方法的实现也就互相交换了
  17. method_exchangeImplementations(safeMethod,sysMethod);
  18. }
  19. + (BOOL)swizzingInstanceMethod:(SEL)originalSelector replaceMethod:(SEL)replaceSelector
  20. {
  21. Method original = class_getInstanceMethod(self, originalSelector);
  22. Method replace = class_getInstanceMethod(self, replaceSelector);
  23. if (!original || !replace) {
  24. return NO;
  25. }
  26. class_addMethod(self, originalSelector, class_getMethodImplementation(self, originalSelector), method_getTypeEncoding(original));
  27. class_addMethod(self, replaceSelector, class_getMethodImplementation(self, replaceSelector), method_getTypeEncoding(replace));
  28. method_exchangeImplementations(original, replace);
  29. return YES;
  30. }
  31. @end