I'm confused on how to implement a singleton in objective-c.
I read this post on stackoverflow and was confused by the code shown as the right answer.
How do I implement an Objective-C singleton that is compatible with ARC?
This code is from the post I link to above.
+ (MyClass *)sharedInstance
{
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
What I don't understand is this single line below.
static MyClass *sharedInstance = nil;
Why does it need to assign "nil" to static variable within the method? If this line is on the top within sharedInstance method, every time it is called, the static variable becomes nil. And because "despatch_once" is only called once, I think this method always return nil after this method is called once.
Could anyone please help me understand how this thing works?
Does the first line of this method also get ignored after the second call?