Last active
August 29, 2015 14:01
-
-
Save vilanovi/688564548c904fd7b2d2 to your computer and use it in GitHub Desktop.
Objective-C selector swizzle
This file contains hidden or 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
// ************************************************************ // | |
// NSObject + Swizzle.h | |
// ************************************************************ // | |
@interface NSObject (Swizzle) | |
+ (void)swizzleSelector:(SEL)selector withSelector:(SEL)newSelector; | |
@end | |
// ************************************************************ // | |
// NSObject + Swizzle.m | |
// ************************************************************ // | |
#import "NSObject+Swizzle.h" | |
#import <objc/runtime.h> | |
@implementation NSObject (Swizzle) | |
+ (void)swizzleSelector:(SEL)selector withSelector:(SEL)newSelector | |
{ | |
Method originalMethod = class_getInstanceMethod(self, selector); | |
Method newMethod = class_getInstanceMethod(self, newSelector); | |
BOOL methodAdded = class_addMethod([self class], | |
selector, | |
method_getImplementation(newMethod), | |
method_getTypeEncoding(newMethod)); | |
if (methodAdded) | |
{ | |
class_replaceMethod([self class], | |
newSelector, | |
method_getImplementation(originalMethod), | |
method_getTypeEncoding(originalMethod)); | |
} | |
else | |
{ | |
method_exchangeImplementations(originalMethod, newMethod); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment