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

Method Swizzling 與 AOP(面向切面編程)實踐

編輯:iOS 開發基礎

上一篇介紹了 Objective-C Messaging。借助 Objective-C 的 Runtime 特性,我們能為語言擴展能力,去解決項目中的一些設計與技術難題。這一篇,我們來探討幾個利用 Runtime 的「黑科技」,其中最富爭議的,或許就是 Method Swizzling。

介紹一項技巧,最好的方式莫過於提出具體需求,再拿它與其他方案做對比。

所以先來看需求:對 App 的用戶行為進行追蹤與分析。簡單說,就是當用戶看到某個 View 或點擊某個 Button 時,把這個事件記錄下來。

手動添加

最直接粗暴的做法,是在每個 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 的主邏輯,可隨着項目膨脹、代碼增多,你的 ViewController 裡會散落各處的 Logging,想找到某段記錄代碼變得困難,甚至動輒忘記添加。

你可能會想到用繼承或類別,在重寫的方法裡插入記錄代碼。比如用類別大概長這樣:

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

Logging 代碼高度相似,靠繼承或類別重寫相關方法確實能把它從主邏輯裡剝離。但問題也隨之而來:

1. 你得繼承 UIViewController、UITableViewController、UICollectionViewController 這一票控制器,或給它們挨個加類別;

2. 每個控制器的 ButtonClick 方法命名不可能完全一致;

3. 你無法控制別人如何實例化你的子類;

4. 對於類別,你沒法調用原來的方法實現——大多數時候,我們重寫只是想「追加」代碼,而非徹底取代;

5. 若兩個類別都實現了同名方法,運行時無法保證調用的是哪一個。

Method Swizzling

Method Swizzling 利用 Runtime,把一個方法的實現與另一個方法的實現相互替換。

上一篇講過,每個類裡都有一張 Dispatch Table,把方法名(SEL)與方法實現(IMP,指向 C 函數的指針)一一對應。Swizzle 一個方法,本質就是在運行時改動這張表,讓某個 SEL 對應到另一個 IMP。

先定義一個類別,加入待 Swizzle 的方法:

@implementation UIViewController (Logging)
- (void)swizzled_viewDidAppear:(BOOL)animated {   // 調用原始實現
    [self swizzled_viewDidAppear:animated];    // Logging
    [Logging logWithEventName:NSStringFromClass([self class])];
}
@end

代碼看着有點像遞歸?其實不然——運行時函數實現已被交換:調用 viewDidAppear: 會走到你實現的 swizzled_viewDidAppear:,而在其中調用 swizzled_viewDidAppear: 實際上執行的是原來的 viewDidAppear:。

接著實現 swizzle 方法本身:

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,若已存在,再用 method_exchangeImplementations 把原實現與新實現交換。

最後,只需確保在程序啟動時調用 swizzleMethod。比如在 UIViewController 的 Logging 類別裡加一個 +load: 方法,在其中把 viewDidAppear 替換掉:

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

一般情況下,類別裡的方法會覆蓋主類中的同名方法;若兩個類別實現了同名方法,只有一個會被調用。但 +load: 是個特例:當一個類被讀入內存時,runtime 會給這個類及其每一個類別都發送 +load: 消息。

其實還能更簡潔:直接用新 IMP 取代原 IMP,而非交換。只要有一個全局函數指針指向原 IMP 即可。

void (gOriginalViewDidAppear)(id, SEL, BOOL);
void newViewDidAppear(UIViewController *self, SEL _cmd, BOOL animated) {
    // 調用原始實現
    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 動態給指定方法追加代碼、以解決橫向關注點的編程方式,就叫做 AOP(Aspect Oriented Programming,面向切面編程)。

Aspect Oriented Programming(面向切面編程)

Wikipedia 對 AOP 的定義是:一個切面可以通過在若干連接點(join point)上應用通知(advice,即附加行為),來改變基礎代碼的行為,而這些連接點由一個稱作切點(pointcut)的表達式來篩選。

在 Objective-C 的世界裡,這句話的意思就是:利用 Runtime 特性給指定方法追加自定義代碼。實現 AOP 的方式有很多,Method Swizzling 便是其一。所幸的是,如今已有一些第三方庫讓你不必深諳 Runtime,也能直接上手 AOP。

Aspects 就是一個不錯的 AOP 庫,它封裝了 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 的 API,之前的例子會蛻變成這樣:

@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];
}
@end

你可以用同樣的方式在任何感興趣的方法裡追加代碼,比如 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];
}
@end

然後在 -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 是個經典應用,這裡拋磚引玉,發揮想象力,你還能玩出更多有趣的花樣。

完整的 Aspects 示例可在此獲取:AspectsDemo。若有問題或想法,歡迎留言或來郵 peng@glowing.com 交流討論。

Reference

method-swizzling;method replacement for fun and profit;Aspects

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