Singleton Creation preference

Posted by cwieland on Stack Overflow See other posts from Stack Overflow or by cwieland
Published on 2012-06-02T04:19:37Z Indexed on 2012/06/02 4:40 UTC
Read the original article Hit count: 95

Filed under:
|
|

You can create singletons in a variety of ways. I am wondering which is better between these.

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

I could see that this compiles down to something very fast. I would think that checking the predicate would be another function call. The other is:

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

Are there any major differences between the two? I know these are probably similar enough to not worry about it. But Just wondering.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about ios