So I have a singleton and Im trying to understand the difference between these two implementations: functionally I have tried running my code with both of them and they both work
However, I notice that in the 1st implementation there is no [self alloc] being called instead the call is to [super alloc]. Im a bit perplexed by this. It seems to work but it seems a bit magical so Im wondering if someone can clarify
1st way:
+(id)getSingleton
{
static dispatch_once_t pred;
dispatch_once(&pred, ^{
locMgrSingleton = [[super alloc] init];
});
return locMgrSingleton;
}
Another way
+(id)getSingleton
{
@synchronized(self)
{
if (locMgrSingleton == nil)
{
locMgrSingleton = [[self alloc]init];
NSLog(@"Created a new locMgrSingleton");
}
else
{
NSLog(@"locMgrSingleton exists");
}
}
return locMgrSingleton;
}
Using
[self alloc]vs[super alloc]makes no difference unless the class also overrides+alloc. That said, it should be calling[self alloc]. I’ll bet it’s callingsuperbecause this was probably adapted from an implementation that override+allocto return a singleton.In any case, the difference between the two patterns, besides
selfvssuper, is explained in my answer to this other question, but in short,dispatch_once()is the modern way to do this. It’s faster than@synchronized, and carries more semantic meaning.