Last active
December 18, 2015 04:09
-
-
Save shnhrrsn/5723701 to your computer and use it in GitHub Desktop.
Swap class selectors with a block
This file contains 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> | |
#import <objc/message.h> | |
SEL SHNSwapSelectorWithBlock(Class class, SEL selector, BOOL isClassMethod, id block) { | |
Method method1 = isClassMethod ? class_getClassMethod(class, selector) : class_getInstanceMethod(class, selector); | |
// Generate new selector to inject | |
SEL newSelector = NSSelectorFromString([@"_swappedBlock_" stringByAppendingString:NSStringFromSelector(selector)]); | |
// Inject the block as method in the class | |
class_addMethod(object_getClass(class), newSelector, imp_implementationWithBlock(block), method_getTypeEncoding(method1)); | |
Method method2 = isClassMethod ? class_getClassMethod(class, newSelector) : class_getInstanceMethod(class, newSelector); | |
if(method2 != NULL) { | |
// Success! Swap the selectors and we're done | |
method_exchangeImplementations(method1, method2); | |
return newSelector; | |
} else { | |
// Something broke :( | |
return NULL; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment