david
david

Reputation: 157

where should I declare the static instance?

what is the difference between these singleton implementations:

  1. declaring static instance outside the sharedManager functions

    @implementation MyManager
    
    static MyManager * manager = nil;
    
    +(instancetype)sharedManager
    {
        @synchronized(self) {
            if(manager==nil){
                manager = [[MyManager alloc]init];
            }
            return manager;
        }
    }
    

    2.

    declaring static instance inside the sharedManager function

    @implementation MyManager
    
             +(instancetype)sharedManager
                {
                    static MyManager * manager = nil;
                    @synchronized(self) {
                        if(manager==nil){
                            manager = [[MyManager alloc]init];
                        }
                        return manager;
    
    
       }
            }
    @end
    
    1. declaring MyManager as extern in the interface

4.

+ (instancetype)sharedManager {
    static MyManager *singleton=nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        singleton = [[self alloc] init];
    });
    return singleton;
}

Upvotes: 1

Views: 67

Answers (1)

rob mayoff
rob mayoff

Reputation: 385890

You should make it a static variable inside the accessor method. This prevents you from accidentally accessing it before it's been properly initialized.

The modern way to initialize a singleton safely is like this:

+ (instancetype)sharedManager {
    static MyManager *singleton;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        singleton = [[self alloc] init];
    });
    return singleton;
}

dispatch_once is significantly faster than @synchronized if the once-block has already been performed.

Upvotes: 2

Related Questions