iOS开发中的Aspects框架

简单使用

我们对Person的类方法和实例方法进行替换

  - (void)eat{
NSLog(@"%s", __func__);
}
+ (void)drink{
NSLog(@"%s", __func__);
}

当我尝试用代码去替换drink方法的时候,

  [Person aspect_hookSelector:@selector(drink) withOptions:AspectPositionAfter usingBlock:^(id <AspectInfo> aspectInfo){
    NSLog(@"喝了之后...");
} error:nil];

控制台打印:

  Aspects: Blog signature <NSMethodSignature: 0x600003823e60> doesn't match (null).   

Aspects是不能对类方法进行替换的。

替换实例方法

  [Person aspect_hookSelector:@selector(eat) withOptions:AspectPositionAfter usingBlock:^(){
    NSLog(@"吃了之后...");
} error:nil];

这里有一个参数:AspectPositionAfter,它表示在原方法之后加入操作就是替换之后的操作。比如原方法只是吃饭,在吃饭之后加上洗碗,那么替换后的新方法的完整操作就是吃饭+洗碗。

代码:

  // 方法替换
[Person aspect_hookSelector:@selector(eat) withOptions:AspectPositionAfter usingBlock:^(){
    NSLog(@"吃了之后...");
} error:nil];
[Person aspect_hookSelector:@selector(drink) withOptions:AspectPositionAfter usingBlock:^(id <AspectInfo> aspectInfo){
    NSLog(@"喝了之后...");
} error:nil];

// 方法调用
Person * p = [Person new];
[p eat];
[Person drink];

打印:

 4.Aspects使用[5349:100752] -[Person eat]
 4.Aspects使用[5349:100752] 吃了之后...
 4.Aspects使用[5349:100752] +[Person drink]

注意

替换操作进行一次就行了,如果替换多次,再调用该方法的时候block中的操作就会执行多次。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。