Reputation: 1416
I am writing a singleton in ObjectiveC and saw this implementation in many sites I looked at. I really do not understand the nil assignment in the first raw. Since the block in dispatch_once (to my humble understanding...), how does this method return the previously assigned value (inside the block) and not nil.
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
P.S - I noticed this question was asked once here but was not resolved and non of the unswears explain this clearly - Why is assigned a nil to singleton's static variable
Upvotes: 0
Views: 225
Reputation: 539745
The sharedMyManager = nil
assignment is not necessary because
static variables are automatically initialized to zero.
You can simply remove it.
In addition, the dispatch_once()
guarantees that sharedMyManager
is assigned
a value before it is used.
Also note that dispatch_once()
uses the fact that the onceToken
is initialized
to zero automatically.
Upvotes: 5
Reputation: 318804
In C based languages, such as Objective-C, static variables are only initialized once. So the nil
assignment only happens the very first time the code is executed.
Then the call to dispatch_once
only happens once (that is its purpose), so the static variable is then set to the desired value just the one time.
Upvotes: 3
Reputation: 8170
If you don't initialize your static variable, it can initially have garbage data.
Static variables are initialized once. So in the +sharedManager
message, the line where the static variable is declared is only run once, and in subsequent calls that line is skipped.
That's why this is the 'standard way' of using static variables inside functions.
Upvotes: -2