Search code examples
iosobjective-cgrand-central-dispatchshared

Singleton class static variable set to nil each time


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.


Solution

  • 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.