Reputation: 339
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
Upvotes: 0
Views: 90
Reputation: 153
the static
keyword extends the lifetime of the variable util the program terminates, even being valid only locally. It also ensures that it will be initialized only once.
void scope()
{
// Without `static`, var1 would be reset to 0 in every call
static TYPE var1 = 0; // Instantiated and initialized only once.
useVar(var1); // Use the variable and possibly change its value
// Even though var1 is only valid in the scope, it retains the last value
}
It has the same behavior as other languages such as C/C++, Java, C#, etc
Upvotes: 1
Reputation: 52538
This is basic C. If you learn Objective-C, you should take a C book and learn the basics about the language.
A static variable, like a global variable, exists once, from the start of the program to the end of the program, and is initialised exactly once at some time before the first access to the variable. That's the basic C rule, which has been like that for the last 40 years or so, and applies to Objective-C as well because it is a superset of C.
What you see is an initialization, not an assignment.
Upvotes: 2