NSObject+Swizzling.m 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. //
  2. // NSObject+Swizzling.m
  3. // assemble
  4. //
  5. // Created by apple on 2020/11/2.
  6. // Copyright © 2020 kingsunsoft. All rights reserved.
  7. //
  8. #import "NSObject+Swizzling.h"
  9. #import <objc/runtime.h>
  10. @implementation NSObject (Swizzling)
  11. + (void)exchangeInstanceMethodWithSelfClass:(Class)selfClass
  12. originalSelector:(SEL)originalSelector
  13. swizzledSelector:(SEL)swizzledSelector {
  14. Method originalMethod = class_getInstanceMethod(selfClass, originalSelector);
  15. Method swizzledMethod = class_getInstanceMethod(selfClass, swizzledSelector);
  16. BOOL didAddMethod = class_addMethod(selfClass,
  17. originalSelector,
  18. method_getImplementation(swizzledMethod),
  19. method_getTypeEncoding(swizzledMethod));
  20. if (didAddMethod) {
  21. class_replaceMethod(selfClass,
  22. swizzledSelector,
  23. method_getImplementation(originalMethod),
  24. method_getTypeEncoding(originalMethod));
  25. } else {
  26. method_exchangeImplementations(originalMethod, swizzledMethod);
  27. }
  28. }
  29. @end