Created
February 28, 2015 23:33
-
-
Save ricardolpd/285eaec0973663f519af to your computer and use it in GitHub Desktop.
NSObject+swizzle.m
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 <Foundation/Foundation.h> | |
@interface NSObject (Swizzle) | |
/** | |
@brief Method that swizzles both instance methods and class methods | |
@param fromMethod original selector | |
@param toMethod method of destination in swizzling. | |
**/ | |
+ (void) swizzleFromSelector:(SEL) fromMethod toSelector:(SEL) toMethod; | |
@end | |
@implementation NSObject (Swizzle) | |
+ (void) swizzleFromSelector:(SEL) fromMethod toSelector:(SEL) toMethod | |
{ | |
//check if methods are instance methods first | |
Method origMethod = class_getInstanceMethod(self, fromMethod); | |
Method newMethod = class_getInstanceMethod(self, toMethod); | |
BOOL isClassMethod = NO; | |
if (!origMethod) | |
{ | |
origMethod = class_getClassMethod(self, fromMethod); | |
isClassMethod = YES; | |
} | |
if (!newMethod) | |
{ | |
newMethod = class_getClassMethod(self,toMethod); | |
isClassMethod = YES; | |
} | |
//to only be used when method is a class method | |
Class c = self; | |
if (isClassMethod) { | |
c = object_getClass((id) self); | |
} | |
if(class_addMethod(c, fromMethod, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) | |
{ | |
class_replaceMethod(c, toMethod, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); | |
} | |
else | |
{ | |
method_exchangeImplementations(origMethod, newMethod); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment