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

用 AOP 攔截取代繼承基類:一次 View 層架構的反思

編輯:iOS 開發基礎

實習期間我習慣把 ViewController 裡的通用邏輯抽到一個基類,其他頁面都去繼承它,一直覺得這是好設計。直到讀到一篇討論 View 層架構的文章,才發現派生基類並不是最佳解。

派生基類的兩個隱性成本

集成成本。當時開發的 App 直接以源碼方式依賴百度地圖與百度導航,編譯一次要好幾分鐘。開發新頁面時必須頻繁 run 起來看效果,光是等編譯就讓人崩潰。想另外做一個乾淨的 Demo,但所有 ViewController 都繼承自同一個基類,而基類又拉了一堆基礎庫,折騰半天還是搭不起來。

學習成本。新人接手時,除了業務本身,還得先學會這個派生基類的種種約定。

改用攔截器

既然繼承不是好答案,就用 AOP 攔截來達到同樣效果。這裡使用現成的 Aspects 庫,建立一個繼承 NSObject 的攔截器:

@implementation ViewControllerInterceptor

// load 會在 App 啟動時由 runtime 自動呼叫,是注入程式碼的合適時機
+ (void)load {
    [super load];
    [ViewControllerInterceptor sharedInstance];
}

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static ViewControllerInterceptor *sharedInstance;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[ViewControllerInterceptor alloc] init];
    });
    return sharedInstance;
}
@end

因為繼承自 NSObject,+load 會在啟動階段被 runtime 呼叫,所以把 Aspects 的掛鉤寫在 -init 裡,由單例保證只執行一次:

- (instancetype)init {
    if ([super init]) {
        // AspectPositionBefore / After / Instead 三種時機可選
        [UIViewController aspect_hookSelector:@selector(viewWillAppear:)
                                  withOptions:AspectPositionAfter
                                   usingBlock:^(id aspectInfo, BOOL animated) {
            UIViewController *vc = [aspectInfo instance];
            [self viewWillAppear:animated viewController:vc];
        } error:NULL];
    }
    return self;
}

這樣一來,任何 UIViewController 執行完 viewWillAppear: 之後都會被攔下,交由攔截器處理:

#pragma mark - fake methods

- (void)viewWillAppear:(BOOL)animated viewController:(UIViewController *)viewController {
    // 原本放在基類裡的通用業務
    if (!viewController.isInitTheme) {
        [self ThemeDidNeedUpdateStyle];
        viewController.isInitTheme = YES;
    }
    // 其他通用操作……
}

- (void)ThemeDidNeedUpdateStyle {
    NSLog(@"Theme did need update style");
}

狀態標記怎麼放

問題來了:主題只該初始化一次,因此需要一個標記位;但被攔截的 ViewController 是不確定的類,總不能回到「每個類都加一份屬性」的舊路。這時 Category 派上用場。

@interface UIViewController (Addition)
@property (nonatomic, assign) BOOL isInitTheme;
@end

再用 runtime 關聯物件把「實例變數」補上去:

#define KeyIsInitTheme @"KeyIsInitTheme"

@implementation UIViewController (Addition)

- (BOOL)isInitTheme {
    return [objc_getAssociatedObject(self, KeyIsInitTheme) boolValue];
}

- (void)setIsInitTheme:(BOOL)isInitTheme {
    objc_setAssociatedObject(self, KeyIsInitTheme, @(isInitTheme),
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

Category 本身不能加 ivar,但關聯物件的效果等同於在每個實例上掛了一個標記。

讓部分頁面豁免攔截

如果某些 ViewController 不希望被處理,只要再補一個開關:

@property (nonatomic, assign) BOOL disabledInterceptor;

一樣用 runtime 實作存取器,然後在攔截成功的 block 裡判斷:

- (instancetype)init {
    if ([super init]) {
        [UIViewController aspect_hookSelector:@selector(viewWillAppear:)
                                  withOptions:AspectPositionAfter
                                   usingBlock:^(id aspectInfo, BOOL animated) {
            UIViewController *vc = [aspectInfo instance];
            if (!vc.disabledInterceptor) {
                [self viewWillAppear:animated viewController:vc];
            }
        } error:NULL];
    }
    return self;
}

這樣做換來了什麼

用攔截取代派生基類,最大的好處是 業務程式碼不再需要主動去迎合框架,改由框架去感知業務。本文只拿 UIViewController 當例子,但同樣的手法完全可以用在其他類上。

當然,這不表示繼承從此可以丟掉——真正需要 is-a 關係時,繼承仍是最合適的選擇。挑對方案才是重點。Demo 已放在 GitHub,需要的自行取用。

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