AOP交换

作者: 又又轻 | 来源:发表于2018-07-23 17:13 被阅读26次
#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

相关文章

网友评论

      本文标题:AOP交换

      本文链接:https://www.haomeiwen.com/subject/vsvjmftx.html