Created
February 9, 2015 18:13
-
-
Save Albertoimpl/04465aef5014484494fc to your computer and use it in GitHub Desktop.
A basic example of method swizzle
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, ^{ | |
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 { | |
NSLog(@"XXXXXXXXXXXXXX viewWillAppear: %@ at %f", self, [[NSDate date] timeIntervalSince1970]); | |
[self xxx_viewWillAppear:animated]; | |
NSLog(@"XXXXXXXXXXXXXX viewWillAppear: %@ at %f", self, [[NSDate date] timeIntervalSince1970]); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment