天天看點

iOS下單例模式實作(一)(objective-c arc gcd)

單例模式確定某一個類隻有一個執行個體,而且自行執行個體化并向整個系統提供這個執行個體。

這裡主要介紹下在arc下,利用gcd實作單例。

第一步:聲明一個靜态執行個體 

static SoundTool *_instance;

第二步:重寫初始化方法

+ (id)allocWithZone:(struct _NSZone *)zone

在對象初始化配置設定記憶體的時候都會調用這個方法,重寫該方法時,即便使用者沒用通過shared方法擷取執行個體,自己初始化依然可以保證得到的是同一個執行個體。

在gcd後,多線程下保證一個代碼隻被執行一次提供了一個便捷的方式就是dispatch_once。

這個代碼方法并不需要認真記憶。在xcode中已經内置了代碼段。敲下dispath_once就會有智能提示。

iOS下單例模式實作(一)(objective-c arc gcd)

第三步:聲明一個類方法共享執行個體

+ (SoundTool *)sharedSoundTool

@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