利用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]; 复制代码