#import "TestClass.h"
@implementation TestClass
-(void) testMethod {
NSLog(@"我是TestMethod的执行结果");
}@end
#import <objc/runtime.h>
@implementation TestClass (Logging)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
id obj = [[self alloc] init];
[obj swizzleMethod: @selector(testMethod)
withMethod: @selector(logTestMethod)];
});
}
- (void)logTestMethod{
[self before];
[self logTestMethod];
[self after];
}
- (void)before {
NSLog(@"调用方法之前要做");
}
- (void)after {
NSLog(@"调用方法之后要做");
}
- (void)swizzleMethod:(SEL)originSEL withMethod:(SEL)newSEL {
Class class = [self class];
Method originalMethod = class_getInstanceMethod(class, originSEL);
Method swizzledMethod = class_getInstanceMethod(class, newSEL);
method_exchangeImplementations(originalMethod, swizzledMethod);
}@end
网友评论