官方定義:Executes a block object once and only once for the lifetime of an application. 在應(yīng)用程序的生命周期內(nèi)執(zhí)行一個(gè)block對象一次且僅僅執(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的指針,用于檢測block是否完成。
block:The block object to execute once. 執(zhí)行一次的block對象准给。
- 詳細(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)用中初始化全局或者單例對象撕攒。在使用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ù)測的問題革半。
- 示例展示:
@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