2012-06-02 39 views
2

您可以通過各種方式創建單身人士。我想知道這些之間哪個更好。單身人士創作偏好

+(ServerConnection*)shared{ 
    static dispatch_once_t pred=0; 
    __strong static id _sharedObject = nil; 
    dispatch_once(&pred, ^{ 
     _sharedObject = [[self alloc] init]; // or some other init method 

    }); 
    return _sharedObject; 
} 

我可以看到,這個編譯速度非常快。我認爲檢查謂詞將是另一個函數調用。 另一種是:

+(ServerConnection*)shared{ 
    static ServerConnection* connection=nil; 
    if (connection==nil) { 
     connection=[[ServerConnection alloc] init]; 
    } 
    return connection; 
} 

有沒有兩者之間有什麼主要區別?我知道這些可能相似,不用擔心。但只是想知道。

回答

2

主要區別在於第一個使用Grand Central Dispatch來確保創建單例的代碼只能運行一次。這向你保證它將是一個單身人士。

此外,GCD應用威脅安全性,因爲根據規範,每次調用dispatch_once都將同步執行。

我會建議這個

+ (ConnectionManagerSingleton*)sharedInstance { 

    static ConnectionManagerSingleton *_sharedInstance; 
    if(!_sharedInstance) { 
     static dispatch_once_t oncePredicate; 
     dispatch_once(&oncePredicate, ^{ 
      _sharedInstance = [[super allocWithZone:nil] init]; 
     }); 
    } 

    return _sharedInstance; 
} 

+ (id)allocWithZone:(NSZone *)zone {  

    return [self sharedInstance]; 
} 

- (id)copyWithZone:(NSZone *)zone { 
    return self;  
} 

從這裏拍攝http://blog.mugunthkumar.com/coding/objective-c-singleton-template-for-xcode-4/

編輯:

這裏的答案是什麼你問 http://cocoasamurai.blogspot.jp/2011/04/singletons-your-doing-them-wrong.html

編輯2 :

上面的代碼是ARC,如果你要非圓弧支持添加

#if (!__has_feature(objc_arc)) 

- (id)retain { 

    return self;  
} 

- (unsigned)retainCount { 
    return UINT_MAX; //denotes an object that cannot be released 
} 

- (void)release { 
    //do nothing 
} 

- (id)autorelease { 

    return self;  
} 
#endif 

(準確的講,第一個鏈接上解釋)

最後約單身一個很好的解釋:

http://csharpindepth.com/Articles/General/Singleton.aspx

+0

正是我所希望的。謝謝! – utahwithak

+1

在手動保留版本中,不要打擾所有忽略廢話。它只會讓後來的重構遠離單身更難,這是一堆額外的完全不必要的代碼。 – bbum