rowana
rowana

Reputation: 748

Usage of dispatch_once

I understand that dispatch_once is something that is equivalent to a static variable and that the piece of code inside dispatch_once is executed only once throughout the application.

I am going through a huge code base and came across something like this

+ (DBHelper *)sharedInstance {

    static DBHelper *sharedDBHelper = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        sharedDBHelper = [[super alloc] initUniqueInstance];
    });

    return sharedDBHelper;
}

DBHelper.sharedInstance is used to get an object and is used in a lot of places ot generate objects.

I'm confused as to why dispatch_once is being used here since that would mean you could have only one object of the class?

Upvotes: 1

Views: 1325

Answers (2)

CRD
CRD

Reputation: 53000

This is the standard pattern for a shared instance, otherwise known as a faux singleton.

In many cases programmers choose to use a single object that can be easily accessed from any part of an application - by calling a static method which returns back a reference to the shared object, i.e. sharedInstance in your example - as a means to provide communication/shared data between otherwise independent parts of the application.

It is a faux singleton pattern as it does not prevent other instances of the same type - DBHelper in your example - from being created. A true singleton model is one in which only a single instance of the type can ever be created. (Apple used to have sample code showing how to create true singletons, but it was never updated for the post-ARC world, for more details on that including an ARC version see this answer.)

HTH

Upvotes: 1

Cesar
Cesar

Reputation: 2057

It's a singleton (a design pattern). You only need one instance of the class instantiated, so that's all you create.

Upvotes: 0

Related Questions