Created
March 7, 2023 16:59
-
-
Save timonus/ea92e5e4390395733c1d9452681d21e4 to your computer and use it in GitHub Desktop.
Swizzling copypasta
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <objc/runtime.h> | |
void tj_swizzle(Class class, SEL originalSelector, SEL swizzledSelector) | |
{ | |
Method originalMethod = class_getInstanceMethod(class, originalSelector); | |
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); | |
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); | |
if (didAddMethod) { | |
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); | |
} else { | |
method_exchangeImplementations(originalMethod, swizzledMethod); | |
} | |
} | |
void tj_swizzleClassMethod(Class class, SEL originalSelector, SEL swizzledSelector) | |
{ | |
Method originalMethod = class_getClassMethod(class, originalSelector); | |
Method swizzledMethod = class_getClassMethod(class, swizzledSelector); | |
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); | |
// if (didAddMethod) { | |
// class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); | |
// } else { | |
method_exchangeImplementations(originalMethod, swizzledMethod); | |
// } | |
} | |
//@interface Class (Hacks) | |
// | |
//@end | |
// | |
//@implementation Class (Hacks) | |
// | |
//+ (void)load | |
//{ | |
// tj_swizzle([self class], ...) | |
//} | |
// | |
//@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment