Reputation: 1558
I am making a singleton class for my use . I have seen code for singleton class is like this:
//First Example
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
//Second Example
static SingletonSample *sharedObject;
+ (SingletonSample*)sharedInstance {
if (sharedObject == nil) {
sharedObject = [[super allocWithZone:NULL] init];
}
return sharedObject;
}
The seconds seems fine and understandable. But i am confused in First example where sharedMyManager is set to nil each time and also there is a allocation of shared manager each time, my doubt is that how will first example return the same reference of the class(Singleton).
Thanks.
Upvotes: 1
Views: 1707
Reputation: 3658
sharedMyManager is set to nil each time
static variables are set only once.
there is a allocation of shared manager each time
You use dispatch_once
, so it's incorrect too.
Read about dispatch_once here. And using GCD is faster and thread safe.
Upvotes: 1
Reputation: 122401
As it's static
it will initially be set to nil
, but in subsequent calls the value will remain to whatever you have set it to in previous calls.
The first example is better as it is thread safe. The second example doesn't even initialise sharedObject
which is dangerous (I don't believe there is a guarantee that global variables are initialised to zero).
Upvotes: 2
Reputation: 17186
First of all when static is declared with in function, it is declared only once. So, the line
static MyManager *sharedMyManager = nil;
Will be executed only once when the function gets called for first time.
In the next line when you use dispath_once
, it will be executed for only once. So the creation of sharedMyManager
will be done once only. So, thats a perfect way to create a single ton class.
Upvotes: 5