標籤:
引子:項目中需要對按鈕點擊事件進行統計分析,現在項目中就是在按鈕的響應代碼中添加點擊事件,非常繁瑣。所以使用了AOP(面向切面編程),將統計的商務邏輯統一抽離出來。
項目中添加的開源庫:https://github.com/steipete/Aspects
Method Swizzling 利用runtime交換了函數 SEL A,IMP A 與 SEL B,IMP B,這一黑魔法使得抽離商務邏輯變的可能。
更多資料可以參考:http://www.cocoachina.com/ios/20150120/10959.html
我處理的過程是建立了一個類用於處理AOP,暫且叫Aspect類
+ (void)load {
[super load];
[Aspect sharedInstance];
}
+ (instancetype)sharedInstance {
static CGAspect *_shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shared = [[CGAspect alloc] init];
});
return _shared;
}
- (instancetype)init
{
self = [super init];
if (self) {
[self CG_hook_UIButton];
}
return self;
}
-(void)CG_hook_UIButton {
[UIButton aspect_hookSelector:@selector(sendAction:to:forEvent:) withOptions:0 usingBlock:^(id<AspectInfo> info) {
UIButton *btn = [info instance];
NSString *str = btn.buriedPointTag;
if (str.length > 0) {
//在這裡處理統計的模組
}
} error:NULL];
}
主要說明一下hook的方法,apects對hook有了很好的封裝,第一參數是需要hook的SEL,第二個參數是一個枚舉狀態,表示你所hook得方法與第三個參數(block)的執行順序,具體可以參見枚舉說明。第三個block參數中可以擷取到info,通過 [info instance]可以擷取到調用的執行個體對象,在這裡是個button。
btn.buriedPointTag的屬性是專門用來處理統計的按鈕的標籤,當然你也可以用原生的tag標籤,我這裡主要是為了完全抽離這裡的邏輯。
以下是為button添加buriedPointTag的方法
- (NSString *)buriedPointTag
{
return objc_getAssociatedObject(self, UIButton_buriedPoint_key);
}
- (void)setBuriedPointTag:(NSString *)buriedPointTag
{
objc_setAssociatedObject(self, UIButton_buriedPoint_key, buriedPointTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
這樣就輕鬆的把按鈕的統計做好,當然你的產品要對別的控制也做統計,你仍然需要去額外處理,你也可以用這種方法對別的類型的統計業務進行抽離,具體情況需要看需求有沒有必要這麼處理。
iOS中AOP與Method Swizzling 項目中的應用