Difference between these two implementations of thread initializers in object C
So I have a singleton and Im trying to figure out the difference between these two implementations: functionally I tried to run my code with both of them and they both work
However, I notice that in the first implementation there is no [self alloc] called instead, it is [super alloc]. I'm a little confused about this. This seems to work, but it seems a bit magical, so I wonder if anyone can clarify
First 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;
}
source to share
Using [self alloc]
vs [super alloc]
doesn't matter as long as the class also overrides +alloc
. However, he has to call [self alloc]
. I'm willing to bet what he's calling super
because this was probably adapted from an implementation that overrides +alloc
to return a singleton.
Anyway, the difference between the two patterns other than self
vs super
is explained in my answer to this other question , but in short, dispatch_once()
it's a modern way of doing it. It is faster than @synchronized
, and has more meaning.
source to share
As indicated in FIG. http://cocoasamurai.blogspot.fi/2011/04/singletons-your-doing-them-wrong.html , the call dispatch_once
just looks a little faster than @synchronized(self)
.
As for the reasons [super alloc]
instead [self alloc]
, I see no reason why it is specific to the version dispatch_once
but not the other. In a static method, it self
just refers to the class itself (and super
its direct superclass), and I would consider it as shorthand for writing the actual class name, nothing more.
I've ever used [self alloc]
it though, since I otherwise wrote the name of the current class and not its superclass. I do not know if the particular challenge has any particular significance [super alloc]
.
source to share
In a class method, self
points to the class itself. In both of your implementations [self alloc]
, [MySingleton alloc]
and are [super alloc]
all semantically equivalent, unless you override for some odd reason +alloc
.
One of the reasons you might want to use [super alloc]
over others is because I explicitly mark the +alloc
inaccessibility in the declaration with a compiler directive:
+(instancetype) alloc __attribute__((unavailable("alloc not available")));
or
+(instancetype) alloc NS_UNAVAILABLE;
Otherwise the compiler will throw an error when trying to +alloc
instantiate your singleton class, which is usually what you want, except when you are a +alloc
generic singleton instance in dispatch_once.
source to share