在ARC下的單例的共享實例訪問器中使用dispatch_once的確切原因是什麼?爲什麼Apple建議使用dispatch_once來實現ARC下的單例模式?
+ (MyClass *)sharedInstance
{
// Static local predicate must be initialized to 0
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
是不是一個壞主意,在後臺異步實例單身?我的意思是,如果我請求共享實例並立即依賴它,會發生什麼情況,但dispatch_once需要等到聖誕節才創建我的對象?它不立即返回正確?至少這似乎是Grand Central Dispatch的重點。
那他們爲什麼要這樣做呢?
'注:靜態和全局變量默認爲零。' – ikkentim 2016-09-13 09:56:32