每天學(xué)習(xí)一個(gè)API:GCD - dispatch_once

每天學(xué)習(xí)一個(gè)API

官方定義:Executes a block object once and only once for the lifetime of an application. 在應(yīng)用程序的生命周期內(nèi)執(zhí)行一個(gè)block對(duì)象一次且僅僅執(zhí)行一次

  • 函數(shù)聲明:

void dispatch_once(dispatch_once_t*predicate, dispatch_block_tblock);

  • 參數(shù)說明:

predicate:A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not. 一個(gè)指向結(jié)構(gòu)體dispatch_once_t的指針,用于檢測(cè)block是否完成。

block:The block object to execute once. 執(zhí)行一次的block對(duì)象。

  • 詳細(xì)說明:

This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.

If called simultaneously from multiple threads, this function waits synchronously until the block has completed.

The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.

該API用于在應(yīng)用中初始化全局或者單例對(duì)象。在使用block中聲明的變量之前,總是需要調(diào)用這個(gè)接口。
多線程同時(shí)調(diào)用這個(gè)接口的時(shí)候,會(huì)進(jìn)行同步等待指導(dǎo)block完成。
predicate參數(shù)必須指向全局變量或者靜態(tài)變量。如果使用automatic或者動(dòng)態(tài)分配變量的話,會(huì)發(fā)生不可預(yù)測(cè)的問題。

  • 示例展示:
@interface UCARDataStorageManager : NSObject

+ (instancetype)shareInstance;

@end

@implementation UCARDataStorageManager

+ (instancetype)shareInstance
{
    static UCARDataStorageManager* instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[UCARDataStorageManager alloc] init];
    });
    return instance;
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容