Skip to content

Instantly share code, notes, and snippets.

@streeter
Created July 27, 2013 00:58
Show Gist options
  • Save streeter/6093201 to your computer and use it in GitHub Desktop.
Save streeter/6093201 to your computer and use it in GitHub Desktop.
Swizzle methods in Objective-C
#import <objc/runtime.h>
static void SwizzleClassMethod(Class klass, SEL original, SEL new)
{
Method origMethod = class_getClassMethod(klass, original);
Method newMethod = class_getClassMethod(klass, new);
if (class_addMethod(klass, original, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
class_replaceMethod(klass, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, newMethod);
}
}
static void SwizzleInstanceMethods(Class klass, SEL original, SEL new)
{
Method origMethod = class_getInstanceMethod(klass, original);
Method newMethod = class_getInstanceMethod(klass, new);
if (class_addMethod(klass, original, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
class_replaceMethod(klass, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, newMethod);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment