AOP的框架使用的是 Aspects,使用plist记录需要挂钩的视图控制器名,事件说明,事件名,方法名。
Aspects
Aspects是iOS平台一个轻量级的面向切面编程(AOP)框架,只包括两个方法:一个类方法,一个实例方法。
+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
- (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
函数使用方式简单易懂,挂钩的方式为三种:
typedef NS_OPTIONS(NSUInteger, AspectOptions) {
AspectPositionAfter = 0, /// 在原始方法后调用(默认)
AspectPositionInstead = 1, /// 替换原始方法
AspectPositionBefore = 2, /// 在原始方法前调用
AspectOptionAutomaticRemoval = 1 << 3 /// 在执行1次后自动移除
};
看一段代码:
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"View Controller %@ will appear animated: %tu", aspectInfo.instance, animated);
} error:NULL];
应该很容易能看出这段代码是对UIViewController的viewWillAppear:进行挂钩,在原始方法执行完成后,打印字符串。
plist记录需要挂钩的功能对应的VC和Function
结构为Dictionary->Array-> Dictionary
首先是对应视图控制器的名字 如图中的ViewController
GLLoggingTrackedEvents 为固定的字段名,内容为Array
Array中包含多个Dictionary, Dictionary中的字段名如下:
- GLLoggingFuncDesc 是事件描述
- GLLoggingFuncName 是事件名
- GLLoggingSelectorName 是方法名
注意: 挂钩使用的是SEL,所以如果方法是需要传入参数的,方法名末尾需要增加":"
挂钩的函数如下(在AppDelegate的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions调用):
+ (void)setupWithConfiguration{
NSDictionary *configs = [self dictionaryFromUserStatisticsConfigPlist];
for (NSString *className in configs) {
Class clazz = NSClassFromString(className);
NSDictionary *config = configs[className];
if (config[GLLoggingTrackedEvents]) {
for (NSDictionary *event in config[GLLoggingTrackedEvents]) {
SEL selector = NSSelectorFromString(event[GLLoggingSelectorName]);
[clazz aspect_hookSelector:selector
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo> aspectInfo) {
// 可以使用任意喜欢的埋点统计方式,这里使用的友盟
[MobClick event:event[GLLoggingFuncName]];
} error:NULL];
}
}
}
}
+ (NSDictionary *)dictionaryFromUserStatisticsConfigPlist
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Logging" ofType:@"plist"];
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
return dic;
}