1 Aspects 简介
Aspects github地址: https://github.com/steipete/Aspects
Aspects 可以很好地实现勾取一个类或者一个对象的某个方法
+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
/// Adds a block of code before/instead/after the current `selector` for a specific instance.
- (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
2 使用示例
主界面如下

2.1 勾取UIViewController 类所有实例的viewWillAppear:方法
2.2 勾取UIControl 类的所有实例的sendAction:to:forEvent:方法
2.3 勾取RootViewController类的rootVC 实例的viewDidLoad 方法
代码如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window = window;
RootViewController *rootVC = [[RootViewController alloc] init];
UINavigationController *rootNav = [[UINavigationController alloc] initWithRootViewController:rootVC];
self.window.rootViewController = rootNav;
[self.window makeKeyAndVisible];
// 勾取 UIViewController 类所有实例的viewWillAppear: 方法
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
UIViewController *tempVC = (UIViewController *)info.instance;
NSLog(@"%@ viewWillAppear",[tempVC class]);
} error:nil];
[UIControl aspect_hookSelector:@selector(sendAction:to:forEvent:) withOptions:AspectPositionBefore usingBlock:^(id<AspectInfo> info){
UIControl *control = (UIControl *)info.instance;
if ([control isKindOfClass:[UIButton class]]) {
UIButton *btn = (UIButton *)control;
NSLog(@"%@",btn.titleLabel.text);
}
} error:nil];
// 勾取rootVC 实例的viewDidLoad 方法
[rootVC aspect_hookSelector:@selector(viewDidLoad) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
NSLog(@"RootViewController viewDidLoad");
} error:nil];
return YES;
}
2.4启动应用就可以看到主界面,输出log如下

可以看到有两条输出,一条是viewDidLoad的输出,一条是RootViewController viewWillAppear的输出
2.5点击第一行进入详情页面如下

2.5.1输出log如下

可以看出又多了一条输出DetailViewController viewWillAppear的输出
2.6点击导航返回主界面,输出log如下

可以看出又多了一条输出RootViewController viewWillAppear的输出
2.7点击最后一行进入按钮页面如下

2.7.1输出log如下

可以看出又多了一条输出BtnViewController viewWillAppear的输出
2.7.2点击惊喜按钮,界面如下

2.7.3输出log如下

可以看出又多了一条输出 惊喜,按钮标题的输出
Aspects 的简单使用就到此结束啦
网友评论