I am trying to understand the reason why the dinpatch_once_t and _sharedObject are not set to 0 and nil respectively upon repeated calls to sharedInstance. It seems to me that the way this is coded, that the local variables would be re-initialized as you can reset a static value, right? What basic of ARC or iOS memory management am I not understanding here?
+ (id)sharedInstance
{
// structure used to test whether the block has completed or not
static dispatch_once_t p = 0;
// initialize sharedObject as nil (first call only)
__strong static id _sharedObject = nil;
// executes a block object once and only once for the lifetime of an application
dispatch_once(&p, ^{
_sharedObject = [[self alloc] init];
});
// returns the same object each time
return _sharedObject;
}
It’s actually a C thing rather than ARC or iOS. It’s an “internal static variable” (a.k.a. local static variable) and its declaration is only processed once. It has scope local to the function but an extended lifespan.