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

Objective-C 單例模式:ARC + GCD(dispatch_once)標準寫法

編輯:iOS 開發綜合

單例模式要解決什麼

單例(Singleton)確保某個類別在整個程式生命週期中只有一個實例,並且由該類別自行負責建立、對外提供這個實例。像使用者設定、網路連線管理、音訊播放器、資料庫連線這些全域唯一的資源,都很適合用單例包裝。

在 MRC 時代,寫單例要處理 allocWithZone:、記憶體洩漏、多執行緒競爭等一堆細節。到了 ARC + GCD 的時代,事情變得非常乾淨。

三步驟完成

第一步:宣告一個靜態實例

static SoundTool *_instance;

第二步:共享實例的類別方法

+ (SoundTool *)sharedSoundTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self new];
    });
    return _instance;
}

第三步(進階):重寫 allocWithZone:

上面那段程式碼已經足夠日常使用。但如果你希望「即使有人刻意呼叫 [[SoundTool alloc] init],拿到的仍然是同一個物件」,就得再攔截一層記憶體配置:

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

把所有程式碼合起來:

#import "SoundTool.h"

@implementation SoundTool

static SoundTool *_instance;

+ (SoundTool *)sharedSoundTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self new];
    });
    return _instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

@end

為什麼是 dispatch_once

dispatch_once 由 GCD 提供,它保證傳入的 block 在多執行緒環境下也只會被執行一次,而且會等待第一次執行完畢才回傳,因此天生具備執行緒安全性與記憶體屏障效果。這比自行用 @synchronized 或 lock 來得輕量,也不必自己維護旗標變數。

另外,這個寫法不必記憶——在 Xcode 中輸入 dispatch_once 並按下補全,程式碼片段就會自動展開。

兩個實務提醒

ARC 下不要寫 autorelease。網路文章常直接複製 MRC 寫法,在 ARC 專案中會編譯失敗。

不建議實作 copyWithZone: 以外的一致化方法。若真要做到「完全無法複製」,可以再覆寫 copy 與 release(MRC),但在 ARC 下通常保持簡潔即可,把重點放在 sharedXxx 這個唯一入口就好。

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