iOS的Aspects简单使用

1.通过cocopods安装Aspects

target 'AspectDemo' do
pod "Aspects"
end

2.包含头文件和实现方法


#import "ViewController.h"
#import "AspectTest.h"
#import 

@interface ViewController ()
@property (nonatomic,strong) id test0Token;
@property (nonatomic,strong) id test1Token;
@property (nonatomic,strong) id test2Token;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.test0Token;
    self.test1Token;
    self.test2Token;
    // Do any additional setup after loading the view.
   NSString *tmp0 = [[AspectTest shareTest] test0];
   NSLog(@"%@",tmp0);
   NSString *tmp1 =   [[AspectTest shareTest] test1:@"test1"];
   NSLog(@"%@",tmp1);
   NSString *tmp2 =  [[AspectTest shareTest] test2:@"test2" bbb:@"bbb"];
   NSLog(@"%@",tmp2);
    
    
    
}


-(void)dealloc{
    [self.test0Token remove];
    [self.test1Token remove];
    [self.test2Token remove];
}

-(id)test0Token{
    
    return [[AspectTest shareTest] aspect_hookSelector:@selector(test0) withOptions:AspectPositionInstead usingBlock:^(id info){
        
        NSString  *data = @"aspectTest0bbbbbbbb";
        NSInvocation *invocation = info.originalInvocation;
        [invocation setReturnValue:&data];
    } error:NULL];
    
    
}

-(id)test1Token{
    
    return [[AspectTest shareTest] aspect_hookSelector:@selector(test1:) withOptions:AspectPositionBefore usingBlock:^(id info, NSString *test1){
      NSString *  test2 = @"ljfkdsajkfljasklfjdks";
        NSInvocation *invocation = info.originalInvocation;
        [invocation setArgument:&test2 atIndex:2];
    } error:NULL];
    
}

-(id)test2Token{
    
    return [[AspectTest shareTest] aspect_hookSelector:@selector(test2:bbb:) withOptions:AspectPositionAfter usingBlock:^(id info,NSString *test2, NSString* bbb){
        NSString  *data = [[@"aspectTest2" stringByAppendingString:test2] stringByAppendingString:bbb];
        NSInvocation *invocation = info.originalInvocation;
        [invocation invoke];
    } error:NULL];
    
}

@end

源码 资源下载

你可能感兴趣的:(Objective-C)