Skip to content

Instantly share code, notes, and snippets.

@yanaMyn
Forked from streeter/swizzle.m
Created June 12, 2019 03:54
Show Gist options
  • Save yanaMyn/58f1e8f31c90358f8bc5d1cedcd103a2 to your computer and use it in GitHub Desktop.
Save yanaMyn/58f1e8f31c90358f8bc5d1cedcd103a2 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