Skip to content

Instantly share code, notes, and snippets.

@timonus
Created March 7, 2023 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timonus/ea92e5e4390395733c1d9452681d21e4 to your computer and use it in GitHub Desktop.
Save timonus/ea92e5e4390395733c1d9452681d21e4 to your computer and use it in GitHub Desktop.
Swizzling copypasta
#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