Skip to content

Instantly share code, notes, and snippets.

@shnhrrsn
Last active December 18, 2015 04:09
Show Gist options
  • Save shnhrrsn/5723701 to your computer and use it in GitHub Desktop.
Save shnhrrsn/5723701 to your computer and use it in GitHub Desktop.
Swap class selectors with a block
#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