Last active
December 10, 2015 14:56
-
-
Save bizz84/950cc51d270fff26ce07 to your computer and use it in GitHub Desktop.
Example of method swizzling on UIViewController
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 <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