GCD 沒有 sleep 式的延時 API,取而代之的是 dispatch_after。而 dispatch_once 則是 GCD 中被使用最廣的函數之一,幾乎所有單例都靠它實現。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)),
dispatch_get_main_queue(),
^{
// 延遲執行的代碼
});
拆解三個參數:
dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)):從現在起經過多少納秒。NSEC_PER_SEC 的定義是 1000000000ull,也就是十億納秒等於一秒。dispatch_get_main_queue():由哪個隊列調度,這裡是主隊列。要注意的是,dispatch_after 是異步的,不會阻塞當前線程。實測可以驗證這一點:
// when:從現在起經過多少納秒
dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
void (^task)(void) = ^{
NSLog(@"%@", [NSThread currentThread]);
};
dispatch_after(when, dispatch_get_main_queue(), task);
// 若 "come here" 先打印,代表是異步
NSLog(@"come here");

把調度隊列換成全局隊列或串行隊列,結果完全相同,可見該函數本身就是異步的。因此延時期間主線程仍可正常響應交互。
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 只會執行一次的初始化代碼
});
dispatch_once_t 在頭文件中的定義是 typedef long dispatch_once_t;。當 token 為 0 時執行 block,之後 token 被改寫,後續呼叫直接跳過。它內部含有一把鎖,性能優於一般的互斥鎖,且是線程安全的。
單例模式保證一個類在整個運行週期內只有一個實例,且易於外界訪問,適合管理全局共享資源。判斷是否為 ARC 環境可以用:
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif
@implementation SoundTools
// 保存唯一實例
static id instance;
// 只分配一次內存
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
// 只初始化一次
+ (instancetype)sharedSoundTools {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- (id)copyWithZone:(NSZone *)zone {
return instance;
}
@end
驗證方式很直觀:先後兩次取得實例並列印地址,結果完全一致。
- (void)viewDidLoad {
[super viewDidLoad];
SoundTools *s1 = [SoundTools sharedSoundTools];
NSLog(@"%p", s1);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
SoundTools *s2 = [SoundTools sharedSoundTools];
NSLog(@"%p", s2);
}
MRC 沒有 ARC 代勞引用計數,因此必須手動覆寫內存管理方法,讓單例「永不釋放」:
static id instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
+ (instancetype)sharedSoundTools {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- (id)copyWithZone:(NSZone *)zone {
return instance;
}
#pragma mark - MRC 內存管理
// 引用計數不減
- (oneway void)release {
// 什麼也不做
}
// 引用計數不增,直接回傳自身
- (instancetype)retain {
return instance;
}
- (instancetype)autorelease {
return instance;
}
// 回報一個極大的引用計數
- (NSUInteger)retainCount {
// limits.h,依 CPU 架構自動對齊整數長度
return ULONG_MAX;
}
今天的專案幾乎都是 ARC,MRC 這套寫法主要出現在維護老專案時;但理解它為什麼要覆寫 retain/release,有助於真正搞懂內存管理的運作方式。