giovedì 13 marzo 2014

ObjectiveC: Create a thread safe singleton

If you need to create a singleton keeping it thread-safe, Apple recommends to use the dispatch_once paradigm.

Below an example taken from a Stackoverflow thread (where a user mention this method is 2 times faster than using the classic synchronized paradigm):

+ (MyClass *)sharedInstance
{
    //  Static local predicate must be initialized to 0
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

Nessun commento:

Posta un commento