iOS-Aspect简单使用(AOP)

使用cocoapods将Aspects添加到project中。

target 'Project' do
    use_frameworks!
    pod 'Aspects', '~> 1.4.1'
end

1.主要使用Aspects 中以下两个方法对project中进行监控

#pragma mark - Public Aspects API
+ (id)aspect_hookSelector:(SEL)selector
                           withOptions:(AspectOptions)options
                            usingBlock:(id)block
                                 error:(NSError **)error {
    return aspect_add((id)self, selector, options, block, error);
}

/// @return A token which allows to later deregister the aspect.
- (id)aspect_hookSelector:(SEL)selector
                           withOptions:(AspectOptions)options
                            usingBlock:(id)block
                                 error:(NSError **)error {
    return aspect_add(self, selector, options, block, error);
}

2.导入头文件

#import 

3.简单的使用示例

+(void)Aspect {
    //如果对project中所有ViewController进行监控。
    //可以对UIViewController中的方法进行勾取。
    //例如:viewWillAppear:、viewDidLoad()等方法。
    [UIViewController aspect_hookSelector:@selector(viewWillAppear:) 
                             withOptions:AspecPositionAfter 
                              usingBlock:^(id info) {
                                  NSStirng *className = NSStringFromClass([[info instance] class]);
                                  NSLog(@"%@",className);
                              } error:NULL];

    //对ViewController中方法的监控
    //例如:对ViewController中dismissHUD:(CGFloat)delayFloat;方法进行监控。
    [ViewController aspect_hookSelector:@selector(dismissHUD:) 
                            withOptions:AspectPositionAfter 
                             usingBlock:^(id info, CGFloat delayFloat) {
                                 //调用的实例对象
                                 id instance = info.instance;

                                 //原始的方法
                                 id invocation = info.originalInvocation;

                                 //参数
                                 id arguments = info.arguments;

                                 //原始的方法,再次调用
                                 [invocation invoke];

                                 //监控方法的参数值
                                 NSLog(@"方法参数值:%f",delayFloat);
                             }error:NULL];
}

你可能感兴趣的:(iOS-Aspect简单使用(AOP))