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;
}

これは非常に高速なものにコンパイルされることがわかりました。述語のチェックは別の関数呼び出しになると思います。もう1つは:

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

2つの間に大きな違いはありますか?私はこれらがおそらくそれについて心配しないのに十分似ていることを知っています。しかし、ただ疑問に思います。

4

1 に答える 1

2

主な違いは、最初のものはGrand Central Dispatchを使用して、シングルトンを作成するコードが1回だけ実行されるようにすることです。これにより、シングルトンになることが保証されます。

また、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

于 2012-06-02T04:27:12.803 に答える