Skip to content

Instantly share code, notes, and snippets.

@Albertoimpl
Created February 9, 2015 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Albertoimpl/04465aef5014484494fc to your computer and use it in GitHub Desktop.
Save Albertoimpl/04465aef5014484494fc to your computer and use it in GitHub Desktop.
A basic example of method swizzle
#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