Why does Apple recommend to use dispatch_once for implementing the singleton pattern under ARC?

What’s the exact reason for using dispatch_once in the shared instance accessor of a singleton under ARC?

+ (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;
}

Isn’t it a bad idea to instantiate the singleton asynchronously in the background? I mean what happens if I request that shared instance and rely on it immediately, but dispatch_once takes until Christmas to create my object? It doesn’t return immediately right? At least that seems to be the whole point of Grand Central Dispatch.

So why are they doing this?

2 Answers
2

Leave a Comment