2012-05-14 116 views
1

我想了解爲什麼dinpatch_once_t和_sharedObject沒有分別設置爲0和nil,因爲對sharedInstance的重複調用。在我看來,這是編碼的方式,局部變量將被重新初始化,因爲你可以重置一個靜態值,對吧? ARC或iOS內存管理的基礎是什麼,我在這裏不理解?iOS中的單身人士

+ (id)sharedInstance 
{ 
// structure used to test whether the block has completed or not 
static dispatch_once_t p = 0; 

// initialize sharedObject as nil (first call only) 
__strong static id _sharedObject = nil; 

// executes a block object once and only once for the lifetime of an application 
dispatch_once(&p, ^{ 
    _sharedObject = [[self alloc] init]; 
}); 

// returns the same object each time 
return _sharedObject; 
} 

回答

7

它實際上是一個C的東西,而不是ARC或iOS。它是一個「內部靜態變量」(a.k.a.本地靜態變量),其聲明只處理一次。它具有本地功能,但延長了使用壽命。