Skip to content

Instantly share code, notes, and snippets.

@bizz84
Last active December 10, 2015 14:56
Show Gist options
  • Save bizz84/950cc51d270fff26ce07 to your computer and use it in GitHub Desktop.
Save bizz84/950cc51d270fff26ce07 to your computer and use it in GitHub Desktop.
Example of method swizzling on UIViewController
#import <objc/runtime.h>
@implementation UIViewController(Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self swizzleOriginalSelector:@selector(performSegueWithIdentifier:sender:)
swizzledSelector:@selector(xxx_performSegueWithIdentifier:sender:)];
[self swizzleOriginalSelector:@selector(viewWillAppear:)
swizzledSelector:@selector(xxx_viewWillAppear:)];
});
}
+ (void)swizzleOriginalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector {
Class class = [self class];
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
#pragma mark - Method Swizzling
- (void)xxx_performSegueWithIdentifier:(NSString *)identifier
sender:(id)sender {
NSLog(@"%@: segue with identifier: %@", NSStringFromClass([self class]), identifier);
[self xxx_performSegueWithIdentifier:identifier sender:sender];
}
- (void)xxx_viewWillAppear:(BOOL)animated {
NSLog(@"class: %@", NSStringFromClass([self class]));
[self xxx_viewWillAppear:animated];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment