剛開始寫 iOS 的時候,只要需要全域變數或全域方法,直覺反應就是把東西塞進 AppDelegate——畢竟它無所不在,透過一行程式碼就能拿到:
[UIApplication sharedApplication].delegate
但寫久了會發現這不是好習慣。AppDelegate 本身有明確職責:處理 App 生命週期事件,例如啟動、進入背景、接收到遠端推送等。把全域狀態與 UI 組裝邏輯一股腦塞進去,會讓這個類越來越腫,職責也越來越模糊。
比較合理的做法是另外開一個專門的輔助類,把「全域要用的東西」集中管理。
// APPHelper.h
@interface APPHelper
+ (APPHelper *)call;
- (void)configureWindow:(UIWindow *)window;
@property (nonatomic, readonly) AppDelegate *delegate;
@property (nonatomic, strong, readonly) UIWindow *window;
@end
// APPHelper.m
@interface APPHelper ()
@end
@implementation APPHelper
- (id)init {
self = [super init];
if (self) {
_delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
}
return self;
}
// 單例入口
+ (APPHelper *)call {
static dispatch_once_t onceQueue;
static APPHelper *appInstance;
dispatch_once(&onceQueue, ^{
appInstance = [[APPHelper alloc] init];
});
return appInstance;
}
- (UIWindow *)window {
return self.delegate.window;
}
// 把根視圖與導覽結構的組裝集中到這裡
- (void)configureWindow:(UIWindow *)window {
UINavigationController *nav = [[UINavigationController alloc] init];
// ... 設定各個 rootViewController ...
window.rootViewController = nav;
}
@end
把標頭檔引入預編譯碼頭(*.pch),並定義一個簡短的巨集作為取用捷徑:
#import "AppHelper.h"
#define APP ([APPHelper call])
之後在專案任何一處都能直接取用,例如幫 window 加上圓角:
// 讓 App 的 window 呈現圓角
APP.window.layer.cornerRadius = 5.0f;
APP.window.layer.masksToBounds = YES;
AppDelegate 回歸單純的事件代理角色,可讀性提高;輔助類有自己的命名空間,全域狀態集中一處,日後要重構或抽換實作只需動一個檔案;透過 dispatch_once 建立的單例也保證了初始化只會發生一次。