AOP: Aspect Oriented Programming 面向切面编程
利用 iOS 的runtime
,我们可以做很多移花接木的事情,让人首先联想到的就是Method Swizzle
,对于Method Swizzle
,这里不展开描述,有兴趣的可以自行深入了解
一个使用起来简单愉快的 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;
AspectPositions
typedef NS_OPTIONS(NSUInteger, AspectOptions) {
AspectPositionAfter = 0, // 在原始实现后调用(default)
AspectPositionInstead = 1, // 将替换原始实现
AspectPositionBefore = 2, // 在原始实现之前调用
AspectOptionAutomaticRemoval = 1 << 3 // 执行一次后移除 Hook
};
AspectInfo
@protocol AspectInfo <NSObject>
- (id)instance;
- (NSInvocation *)originalInvocation;
- (NSArray *)arguments;
@end
/** 统计页面的访问量 */
[UIViewController aspect_hookSelector:@selector(viewDidAppear:)
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo> aspectInfo){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *className = NSStringFromClass([[aspectInfo instance] class]);
[self doSomething];
});
} error:NULL];