iOS中AOP與Method Swizzling 項目中的應用

來源:互聯網
上載者:User

標籤:

引子:項目中需要對按鈕點擊事件進行統計分析,現在項目中就是在按鈕的響應代碼中添加點擊事件,非常繁瑣。所以使用了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 項目中的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.