Skip to content

Instantly share code, notes, and snippets.

@acoomans
Created February 2, 2014 04:18
Show Gist options
  • Save acoomans/8763015 to your computer and use it in GitHub Desktop.
Save acoomans/8763015 to your computer and use it in GitHub Desktop.
Objective-C Method Swizzling
// source: https://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html
#import <objc/runtime.h>
void __attribute__((weak)) MethodSwizzle(Class c, SEL origSEL, SEL overrideSEL) {
Method origMethod = class_getInstanceMethod(c, origSEL);
Method overrideMethod = class_getInstanceMethod(c, overrideSEL);
if (class_addMethod(c, origSEL, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(c, overrideSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, overrideMethod);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment