iOS 关于YZHookHandler

YZHookHandler 是什么?

YZHookHandler 是 iOS 上的一个轻量级 AOP 库。它利用 method swizzling 技术为已有的类或者实例方法添加额外的代码,大部分源码代码来自ReactiveObjC ,作者在这个基础上做了二次开发,以便更方便的去使用。

怎么使用 YZHookHandler

- (YZHookHandler *)yz_hookForSelector:(SEL)selector;

- (YZHookHandler *)yz_hookForSelector:(SEL)selector fromProtocol:(Protocol *)protocol;

使用上述两个方法得到YZHookHandler,在YZHookHandler内有三个方法:

/// Called after the original implementation
- (YZHookHandler *)after:(YZHookArgsBlock)after;
/// Will replace the original implementation.
- (YZHookHandler *)instead:(YZHookArgsBlock)instead;
/// Called before the original implementation.
- (YZHookHandler *)befor:(YZHookArgsBlock)befor;
///Remove the current hook.
- (void)removeHook;

YZHookArgsBlock是一个block,在成功hook后将响应带回对应的参数。
其中dealloc是不允许被hook的。

///Hook selector alias prefix, default is yz_alias.
@property (class, nonatomic, copy) NSString *yz_hookHandlerForSelectorAliasPrefix;
///Swizzle subclass suffix, default is _YZHookHandler.
@property (class, nonatomic, copy) NSString *yz_subclassSuffix;

另外你可以自定义方法的前缀和子类化对象的前缀

简单的使用
    YZTest *test1 = [YZTest new];
    
    __weak YZTest *weakTest1 = test1;
    [[[weakTest1 yz_hookForSelector:@selector(test)] after:^(NSArray * _Nonnull args) {
        NSLog(@"after %@",weakTest1);
    }] befor:^(NSArray * _Nonnull args) {
        NSLog(@"befor %@",weakTest1);
    }] ;
    
    [test1 test];
    
    
    NSObject.yz_subclassSuffix = @"_test";
    NSObject.yz_hookHandlerForSelectorAliasPrefix = @"test_";
    
    YZTest *test2 = [YZTest new];
    
    [[test2 yz_hookForSelector:@selector(test)] after:^(NSArray * _Nonnull args) {

    }];
    
    [test2 test];

总结

你可能感兴趣的:(iOS 关于YZHookHandler)