您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

Method Swizzling 與 AOP 實踐:用 Runtime 機制分離橫切關注點

編輯:iOS 開發基礎

上一篇談的是 Objective-C Messaging。既然 Runtime 讓我們能對語言本身做擴充,那麼它也能被拿來解決專案裡一些結構性、跨層面的問題。這一篇要聊的,是 Runtime 裡爭議最大的技巧之一:Method Swizzling。

介紹一個技巧最好的方式,是先丟出一個具體需求,再把它和其他解法放在一起比較。

需求很典型:對 App 的用戶行為做追蹤與分析。也就是說,當使用者看到某個畫面、或點了某顆按鈕時,我們要把這個事件記錄下來。

做法一:到處手動埋點

最直接的做法,是在每個 viewDidAppear 裡補一段記錄事件的通知。

@implementation MyViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // Custom code
    // Logging
    [Logging logWithEventName:@“my view did appear”];
}

- (void)myButtonClicked:(id)sender {
    // Custom code
    // Logging
    [Logging logWithEventName:@“my button clicked”];
}

缺點很明顯:它把程式碼弄髒了。Logging 本身並不屬於 ViewController 的主要邏輯,卻散落在每個方法裡。專案一大,埋點程式碼便四處蔓生,想找某段記錄變得困難,也很容易漏埋。

你可能會想到用繼承或 Category,在覆寫的方法裡統一加上記錄:

@implementation UIViewController (Logging)

- (void)myViewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // Custom code
    // Logging
    [Logging logWithEventName:NSStringFromClass([self class])];
}

- (void)myButtonClicked:(id)sender {
    // Custom code
    // Logging
    NSString *name = [NSString stringWithFormat:@“my button in %@ is clicked”, NSStringFromClass([self class])];
    [Logging logWithEventName:name];
}

這確實能把 Logging 從主邏輯裡剝離,但代價是換來一堆新問題:

  1. 你得為 UIViewController、UITableViewController、UICollectionViewController 全部繼承一遍,或全部加上 Category;
  2. 每個 ViewController 裡的按鈕回呼方法名稱不可能一致;
  3. 你無法控制其他人怎麼實例化你的子類;
  4. Category 沒辦法呼叫到原本的實作,而我們多半只是想「多做一些事」,不是要完全取代原方法;
  5. 若有兩個 Category 實作了同名方法,執行期無法保證哪一個會被呼叫。

做法二:Method Swizzling

Method Swizzling 的做法,是在執行期把一個方法的實作與另一個方法的實作對調。

每個類別都有一張 Dispatch Table,把方法名稱(SEL)與方法實作(IMP,指向 C 函式的指標)一一對應。Swizzle 一個方法,就是在程式跑起來之後改動這張表,讓某個 SEL 指向另一個 IMP。

先寫一個 Category,放入準備被 swizzle 的方法:

@implementation UIViewController (Logging)

- (void)swizzled_viewDidAppear:(BOOL)animated {
    // call original implementation
    [self swizzled_viewDidAppear:animated];
    // Logging
    [Logging logWithEventName:NSStringFromClass([self class])];
}

這段看起來像遞迴,其實不是。因為在 runtime 階段實作已經對調過了:外部呼叫 viewDidAppear: 會走進你的 swizzled_viewDidAppear:,而在其中呼叫 swizzled_viewDidAppear: 時,實際被觸發的卻是原本的 viewDidAppear:。

接著實作負責交換的邏輯:

@implementation UIViewController (Logging)

void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector) {
    // 原方法可能不存在於目前類別,而是繼承自父類
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    // 若原方法已存在,class_addMethod 會失敗
    BOOL didAddMethod = class_addMethod(class,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    // 原本沒有這個方法,是我們剛加上去的
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

唯一需要多解釋一句的是 class_addMethod。之所以先嘗試「新增」原 selector,是一層保護:如果目前類別沒有實作 originalSelector,而父類有,class_getInstanceMethod 會回傳父類的方法,此時 method_exchangeImplementations 就會把父類的實作換掉——這顯然不是我們想要的。所以先試著補上 originalSelector,若已存在,再進行交換。

最後,只要保證在 App 啟動時呼叫一次 swizzleMethod 即可。最常見的位置是在同一個 Category 裡實作 +load:

@implementation UIViewController (Logging)

+ (void)load {
    swizzleMethod([self class], @selector(viewDidAppear:), @selector(swizzled_viewDidAppear:));
}

一般情況下,Category 裡的實作會蓋掉主類別的同名方法;若兩個 Category 實作同名方法,只有一個會生效。但 +load 是例外:當類別被載入記憶體時,runtime 會向這個類別及其每一個 Category 各送一次 +load 訊息。

其實還能再簡化:不交換,而是直接用新的 IMP 覆蓋舊的,只要用一個全域函式指標保留原 IMP 即可。

void (gOriginalViewDidAppear)(id, SEL, BOOL);

void newViewDidAppear(UIViewController *self, SEL _cmd, BOOL animated) {
    // call original implementation
    gOriginalViewDidAppear(self, _cmd, animated);
    // Logging
    [Logging logWithEventName:NSStringFromClass([self class])];
}

+ (void)load {
    Method originalMethod = class_getInstanceMethod(self, @selector(viewDidAppear:));
    gOriginalViewDidAppear = (void *)method_getImplementation(originalMethod);

    if (!class_addMethod(self, @selector(viewDidAppear:), (IMP)newViewDidAppear, method_getTypeEncoding(originalMethod))) {
        method_setImplementation(originalMethod, (IMP)newViewDidAppear);
    }
}

透過 Method Swizzling,我們成功把埋點邏輯與事件處理邏輯解耦。除了 Logging,驗證(Authentication)、快取(Caching)也屬於同一類。這些事務零碎、與主要商業邏輯無關、卻散落在各處,又難以抽成獨立模組——業界稱之為 Cross Cutting Concerns(橫切關注點)。

而用 Method Swizzling 這類動態附加程式碼的手法來處理橫切關注點,就是 Aspect Oriented Programming(AOP,面向切面程式設計)。

Aspect Oriented Programming

Wikipedia 的定義是:

“An aspect can alter the behavior of the base code by applying advice (additional behavior) at various join points (points in a program) specified in a quantification or query called a pointcut (that detects whether a given join point matches).”

放到 Objective-C 的世界裡,這句話的意思就是:利用 Runtime 特性,為指定的方法附加自訂程式碼。AOP 有多種實作方式,Method Swizzling 只是其中之一。幸運的是,已經有現成的第三方庫把這些細節封裝起來,讓你不必碰 Runtime 就能上手。

Aspects 就是其中不錯的選擇,它把 Runtime 與 Method Swizzling 這些「黑魔法」藏在內部,只對外開放了兩個 API:

+ (id)aspect_hookSelector:(SEL)selector
              withOptions:(AspectOptions)options
               usingBlock:(id)block
                    error:(NSError **)error;

- (id)aspect_hookSelector:(SEL)selector
              withOptions:(AspectOptions)options
               usingBlock:(id)block
                    error:(NSError **)error;

換成 Aspects 之後,前面那段例子會變成這樣:

@implementation UIViewController (Logging)

+ (void)load {
    [UIViewController aspect_hookSelector:@selector(viewDidAppear:)
                              withOptions:AspectPositionAfter
                               usingBlock:^(id aspectInfo) {
        NSString *className = NSStringFromClass([[aspectInfo instance] class]);
        [Logging logWithEventName:className];
    } error:NULL];
}

同樣的手法可以用在任何你有興趣的方法上,例如 IBAction 回呼。更好的做法是提供一份 Logging 設定檔,把所有埋點集中管理:

@implementation AppDelegate (Logging)

+ (void)setupLogging {
    NSDictionary *config = @{
        @"MainViewController": @{
            GLLoggingPageImpression: @"page imp - main page",
            GLLoggingTrackedEvents: @[
                @{
                    GLLoggingEventName: @"button one clicked",
                    GLLoggingEventSelectorName: @"buttonOneClicked:",
                    GLLoggingEventHandlerBlock: ^(id aspectInfo) {
                        [Logging logWithEventName:@"button one clicked"];
                    },
                },
                @{
                    GLLoggingEventName: @"button two clicked",
                    GLLoggingEventSelectorName: @"buttonTwoClicked:",
                    GLLoggingEventHandlerBlock: ^(id aspectInfo) {
                        [Logging logWithEventName:@"button two clicked"];
                    },
                },
            ],
        },
        @"DetailViewController": @{
            GLLoggingPageImpression: @"page imp - detail page",
        }
    };
    [AppDelegate setupWithConfiguration:config];
}

+ (void)setupWithConfiguration:(NSDictionary *)configs {
    // Hook 頁面曝光
    [UIViewController aspect_hookSelector:@selector(viewDidAppear:)
                              withOptions:AspectPositionAfter
                               usingBlock:^(id aspectInfo) {
        NSString *className = NSStringFromClass([[aspectInfo instance] class]);
        [Logging logWithEventName:className];
    } error:NULL];

    // Hook 各類事件
    for (NSString *className in configs) {
        Class clazz = NSClassFromString(className);
        NSDictionary *config = configs[className];

        if (config[GLLoggingTrackedEvents]) {
            for (NSDictionary *event in config[GLLoggingTrackedEvents]) {
                SEL selector = NSSelectorFromString(event[GLLoggingEventSelectorName]);
                AspectHandlerBlock block = event[GLLoggingEventHandlerBlock];
                [clazz aspect_hookSelector:selector
                               withOptions:AspectPositionAfter
                                usingBlock:^(id aspectInfo) {
                    block(aspectInfo);
                } error:NULL];
            }
        }
    }
}

然後在 -application:didFinishLaunchingWithOptions: 呼叫 setupLogging:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self setupLogging];
    return YES;
}

結語

靠著 Objective-C Runtime 與 AOP,我們能把零碎的橫切邏輯從主流程中抽離,獨立成一個模組,這是對物件導向典範相當好的一種補充。Logging 只是最經典的切入點,往下延伸還有稽核、權限、效能監控、A/B 測試等場景,值得發揮想像力。

使用 Aspects 的完整範例可參考 AspectsDemo。

參考資料

method-swizzling
method replacement for fun and profit
Aspects

最後提醒一句:Swizzling 是在執行期改寫方法對應關係,威力大、副作用也大。實作時請務必在 +load 或 +initialize 中完成、保持冪等、呼叫原本實作,並避免與系統私有方法命名衝突,否則很容易出現難以追蹤的诡异 bug。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved