Search code examples
iphoneobjective-ciossingletonshared

What is best way to share class instance (create and share singleton)?


I know 2 ways. What is better? And anything better than 2 ways?

+ (MyClass *)shared {
    /*
    static MyClass *sharedInstance = nil;

    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
        }
    }
    return sharedInstance;
    */

    /*
    static dispatch_once_t pred;
    static MyClass *sharedInstance = nil;

    dispatch_once(&pred, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
    */ 
} 

Solution

  • Here is another way to setup you shared instance. Thread safety is handled by the runtime and the code is very straight forward. This is usually how I setup my singletons. If the singleton object uses lots of resources but may not used then the dispatch_once approach works well.

    static MyClass *sharedInstance = nil;
    
    + (void) initialize 
    {
       sharedInstance = [[MyClass alloc] init];
    }
    
    + (MyClass*)sharedInstance   
    {
        return sharedInstance;
    }