Singleton Creation preference
- by cwieland
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.