2017-02-27 21 views
-1
+ (instancetype)sharedInstance 
{ 
    static MyClass *sharedInstance = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     sharedInstance = [[MyClass alloc] init]; 
     // Do any other initialisation stuff here 
    }); 
    return sharedInstance; 

}我對執行一個Objective-C單例模式有一個困惑嗎?

在上面的代碼中偏離航向的時候,每次我們調用的方法,我們會得到相同的地址。但我的問題是,當上述方法第二次調用時,爲什麼不將它分配給sharedInstance對象? (靜態MyClass * sharedInstance = nil;)它是如何返回以前的地址?這可能是一個愚蠢的問題,但我很困惑,請任何人解釋我

回答

0

它被聲明爲一個靜態變量。靜態變量只獲取一次內存。這就是爲什麼每當你調用上述方法時它返回相同的地址

而dispatch_once將在應用程序的生命週期中只執行一次塊。

+0

謝謝你@Dhivya –