さまざまな方法でシングルトンを作成できます。私はこれらの間でどちらが良いのだろうかと思っています。
+(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;
}
これは非常に高速なものにコンパイルされることがわかりました。述語のチェックは別の関数呼び出しになると思います。もう1つは:
+(ServerConnection*)shared{
static ServerConnection* connection=nil;
if (connection==nil) {
connection=[[ServerConnection alloc] init];
}
return connection;
}
2つの間に大きな違いはありますか?私はこれらがおそらくそれについて心配しないのに十分似ていることを知っています。しかし、ただ疑問に思います。