Given these two methods of creating singletons, with the first being thread safe and the second not being thread safe, I would like to know how, each time they are invoked, the "shared instance" isn't set back to nil. I know it isn't, but I'd like to know why. I figure it has something to do with the static keyword, but I'd like a deeper understanding.
thread safe instance
+ (instancetype)sharedInstance {
static id _sharedInstance = nil; //why isn't it set to nil every time
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
non-thread safe instance
+ (instancetype)sharedManager
{
static PhotoManager *sharedPhotoManager = nil; //why isn't set to nil every time
if (!sharedPhotoManager) {
sharedPhotoManager = [[PhotoManager alloc] init];
sharedPhotoManager->_photosArray = [NSMutableArray array];
}
return sharedPhotoManager;
}
Thanks for your help in advance