Aspects 是一个用于面向方面编程的简单、令人愉悦的库。
YLHook 使得 Aspects 支持函数式编程。
我们经常编写大量代码来打印日志或执行统计信息。AOP 提供了一种简洁的方式来解决这些 交叉关注点。
Aspects 示例
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionBefore usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"[%@]before viewWillAppear",[[aspectInfo instance] class]);
} error:NULL];
实际上非常简单。但是,当我们需要在同一类中钩取许多方法时,它就不那么干净了。
这将像这样
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"[%@]after viewWillAppear",[[aspectInfo instance] class]);
} error:NULL];
[UIViewController aspect_hookSelector:@selector(viewDidLoad:) withOptions:AspectPositionBefore usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"[%@]before viewDidLoad",[[aspectInfo instance] class]);
} error:NULL];
[UIViewController aspect_hookSelector:@selector(viewDidAppear:) withOptions:AspectPositionBefore usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"[%@]before viewDidAppear",[[aspectInfo instance] class]);
} error:NULL];
现在,您可以通过这种方式钩取方法
[UIViewController yl_makeEvents:^(YLHookEventMaker *make) {
make.after.sel(viewDidLoad).block(^(id<AspectInfo> aspectInfo){
NSLog(@"[%@]after viewDidLoad",[[aspectInfo instance] class]);
});
make.before.sel(viewWillAppear:).block(^(id<AspectInfo> aspectInfo){
NSLog(@"[%@]before viewWillAppear",[[aspectInfo instance] class]);
});
make.before.sel(viewDidAppear:).block(^(id<AspectInfo> aspectInfo){
NSLog(@"[%@]before viewDidAppear",[[aspectInfo instance] class]);
});
}];
这种风格类似于 Masonry。实际上,我确实参考了 Masonry 的实现。
您可以通过以下静态方法轻松地获取 YLHook 的实例
+ (YLHook *)hookClass:(Class)cls;
+ (YLHook *)hookClassByName:(NSString *)name;
+ (YLHook *)hookInstance:(id)instance;
[[YLHook hookClassByName:@"UIViewController"] makeEvents:^(YLHookEventMaker *make) {
make.before.sel(viewDidAppear:).block(^(id<AspectInfo> aspectInfo){
NSLog(@"[%@]before viewDidAppear",[[aspectInfo instance] class]);
});
}];
\\ or
[UIViewController yl_makeEvents:^(YLHookEventMaker *make) {
make.before.sel(viewDidAppear:).block(^(id<AspectInfo> aspectInfo){
NSLog(@"[%@]before viewDidAppear",[[aspectInfo instance] class]);
});
}];
YLHookEvent
的 execute
是一个可选语义填充,类似于 Masonry 中的 with
。
如果您使用 Cocoapods,请将 pod 'YLHook', '~> 1.0.1'
添加到 Podfile 中。
如果不使用 Cocoapods,将两个文件 YLHook.h/m
拖入您的项目中。此库依赖于 Aspects。您还需要将 Aspects.h/m
拖入到您的项目中。
YLHook 在 MIT 许可下发布。有关详细信息,请参阅 LICENSE。
sel
而不是 selector
。并且不再需要写出 @""
。