AOP(Aspect-Oriented Programming)切面编程在编程中热点话题之一,通过AOP可以对业务逻辑的各个部分进行隔离,降低业务逻辑之间的耦合度,提高程序重用性,同时提高开发效率.
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.)
AOP不是新的技术,是OOP的一种延续,作为切入方向,可以降低公用模块和业务逻辑的之间的耦合关系,开发中实际应用场景:日志记录,性能统计,安全控制,事务处理,异常处理...,对于这些通用功能如果直接嵌套在已有的项目中,不断会影响开发效率,而且会导致后期项目的可读性和维护性都大打折扣.
Method Swizzling
Objective-C 中实现AOP可以通过利用 Runtime 特性给指定的方法添加自定义代码。Method Swizzling 其实很常见,就是在load的时候将两个方法的实现进行交换,第三方库全屏返回手势就是通过交换viewWillAppear实现的.
新增UIViewController分类,方法交换:
<pre><code>`@implementation UIViewController (AOP)
- (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
id obj = [[self alloc] init];
[obj swizzleMethod:@selector(viewWillAppear:) withMethod:@selector(aop_viewWillAppear:)];
[obj swizzleMethod:@selector(viewDidAppear:) withMethod:@selector(aop_viewDidAppear:)];
});
}
(void)aop_viewWillAppear:(BOOL)animated {
NSLog(@"FlyElephant--aop_viewWillAppear方法执行");
}(void)aop_viewDidAppear:(BOOL)test {
NSLog(@"FlyElephant--aop_viewDidAppear方法执行");
}-
(void)swizzleMethod:(SEL)origSelector withMethod:(SEL)newSelector {
Class class = [self class];Method originalMethod = class_getInstanceMethod(class, origSelector);
Method swizzledMethod = class_getInstanceMethod(class, newSelector);BOOL didAddMethod = class_addMethod(class,
origSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
newSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
@end`</code></pre>
ViewController中方法注意要实现父类方法:
<pre><code>`- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"viewWillAppear---正常显示");
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"viewDidAppear---正常展示");
}`</code></pre>
Aspects
Aspects是一个常用的AOP库,通过Runtime封装了两个简单的API,类方法和实例方法.
<pre><code>`+ (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;`</code></pre>
viewDidAppear之后设置回调:
<pre><code>[self aspect_hookSelector:@selector(viewDidAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info) { NSLog(@"viewDidAppear---执行完成之后的回调:%@",info); } error:nil];
</code></pre>
实现按钮点击之后的事件获取:
<pre><code>` [self aspect_hookSelector:@selector(buyAction:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info,NSDictionary *dict){
NSLog(@"FlyElephant---购买的参数:%@",info.arguments);
} error:nil];
[self aspect_hookSelector:@selector(goBuy:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info,NSDictionary *dict){
NSLog(@"FlyElephant---参数:%@",info.arguments);
NSLog(@"FlyElephant---参数:%@",dict);
} error:nil];`</code></pre>
点击执行代码:
<pre><code>`- (IBAction)buyAction:(UIButton *)sender {
NSDictionary *dict = @{@"productName":@"apple"};
[self goBuy:dict];
}
- (void)goBuy:(NSDictionary *)dict {
NSLog(@"购买开始啦");
}`</code></pre>
AOP在埋点开发中会涉及到很多公用的业务,如果每次都在代码中嵌入Aspect代码,可以进行再一次封装.
<pre><code>`static NSString * const MobEventClassName = @"MobEventClassName";
static NSString * const MobEventClassDescription = @"MobEventClassDescription";
static NSString * const MobEventClassEvents = @"MobEventClassEvents";
static NSString * const MobEventClassEventName = @"MobEventClassEventName";
static NSString * const MobEventSelectorName = @"MobEventSelectorName";
static NSString * const MobEventSelectorBlock = @"MobEventSelectorBlock";
@interface AppDelegate (MobEvent)
- (void)setupAnalytics:(NSDictionary *)configs;
@end`</code></pre>
<pre><code>`typedef void (^AspectHandlerBlock)(id<AspectInfo> aspectInfo);
@implementation AppDelegate (MobEvent)
- (void)setupAnalytics:(NSDictionary *)configs {
// Hook Page Impression
// Hook Events
for (NSString *className in configs) {
Class clazz = NSClassFromString(className);
NSDictionary *config = configs[className];
if (config[MobEventClassEvents]) {
for (NSDictionary *event in config[MobEventClassEvents]) {
SEL selekor = NSSelectorFromString(event[MobEventSelectorName]);
AspectHandlerBlock block = event[MobEventSelectorBlock];
[clazz aspect_hookSelector:selekor
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo> aspectInfo) {
// 也可以不设置Block
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
block(aspectInfo);
});
} error:NULL];
}
}
}
}
@end`</code></pre>
AppDelegate中初始化代码:
<pre><code>`- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSDictionary *config = @{
@"ViewController": @{
MobEventClassDescription: @"首页",
MobEventClassEvents: @[
@{
MobEventClassEventName: @"首页Didload进入",
MobEventSelectorName: @"viewDidLoad",
MobEventSelectorBlock: ^(id<AspectInfo> aspectInfo) {
NSLog(@"Config代理执行");
},
}
]
}
};
[self setupAnalytics:config];
return YES;
}`</cod></pre>
实际开发中第一种和第二种都可能需要结合起来,并不是单一的就是满足开发中各种业务需求~