I’ve seen this particular implementation of the singleton pattern everywhere:
+ (CargoBay *)sharedManager {
static CargoBay *_sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedManager = [[CargoBay alloc] init];
});
return _sharedManager;
}
and it seems to be accepted as good practice (this one in particular is from CargoBay).
The only part I don’t understand is the first line static CargoBay *_sharedManager = nil;.
Why are you setting that static variable to nil?
It’s just a matter of readability, convention and practice. It’s not really needed, because:
One. Its value won’t ever be checked. In older singleton implementations there used to be the famous
code – for this method to work, the backing variable has to be initialized to nil, since if it wasn’t nil for the first time, it would falsely omit the alloc-init in the if part and return a junk pointer. However, with the GCD solution, the nil-check is not anymore needed – GCD handles the ‘execute this code only once’ pragma.
Two. But nevertheless: static variables are implicitly initialized to zero. So even if you just write
static id shared;it will initially benil.Three. Why this might be good practice? Because, despite the first two reasons I mentioned, it’s still more readable to let the reader of the source code know that something is explicitly initialized to zero. Or there may even exist some non-conforming implementations where static variables are not properly autoinitialized, and then this action shall be taken.