I came from another programming language. I can understand singleton pattern. But I got confusion in ObjectiveC's Singleton Implementation.
Actually, I understand the lifetime of a static variable. But What makes a static variable initialize only once?
@implementation MyManager
+(instancetype)sharedInstance {
// structure used to test whether the block has completed or not
//Doubt 1 - If this method called second time, how it is not reset again to 0. How it is not executed second time?
static dispatch_once_t p = 0;
// initialize sharedObject as nil (first call only)
//Doubt 2 - If this method called second time, how it is not reset again to nil, How it is not executed second time?
__strong static MyManager * _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;
}
@end