Skip to content

Instantly share code, notes, and snippets.

@vilanovi
Last active August 29, 2015 14:01
Show Gist options
  • Save vilanovi/688564548c904fd7b2d2 to your computer and use it in GitHub Desktop.
Save vilanovi/688564548c904fd7b2d2 to your computer and use it in GitHub Desktop.
Objective-C selector swizzle
// ************************************************************ //
// 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