Created
December 2, 2015 17:20
-
-
Save lonelytango/51a601e2ee08ae4ca209 to your computer and use it in GitHub Desktop.
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
#import <objc/runtime.h> | |
@implementation UIViewController (Tracking) | |
+ (void)load { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
Class class = [self class]; | |
SEL originalSelector = @selector(viewWillAppear:); | |
SEL swizzledSelector = @selector(xxx_viewWillAppear:); | |
Method originalMethod = class_getInstanceMethod(class, originalSelector); | |
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); | |
// When swizzling a class method, use the following: | |
// Class class = object_getClass((id)self); | |
// ... | |
// Method originalMethod = class_getClassMethod(class, originalSelector); | |
// Method swizzledMethod = class_getClassMethod(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_viewWillAppear:(BOOL)animated { | |
[self xxx_viewWillAppear:animated]; | |
NSLog(@"viewWillAppear: %@", self); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment