Object-C – Singleton

Singleton is a design pattern that guarantees that only a single instance of a class exists at any time. Singleton classes are good for Models and Datasources. The singleton is a great partner with a UITableView as the datasource for the tableview.

In the header file declare a class method that will return the shared instance. The shared instance is the single instance of this class that will exist. This method is also responsible for creating the new instance the first time the method is invoked.

+(id)sharedManager;

Define this method in the implementation file.

+(id)sharedManager {
    static Things *sharedThings = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedThings = [[self alloc] init];
    });
    return sharedThings;
}

In the sharedManager method declare the variable sharedThings as static. A static variable remembers its value across invocationsĀ of a function. That is, the value is set the first time the function is called, and that value is “remembered” the next time the function is called. Normally you would expect that the variable would be forgotten on each subsequent invocation.

The dispatch_once guarantees that the block is contains is only executed once. In the example sharedThings should only be created once, the first time sharedManager is invoked.

The last step is to return the sharedThings instance.

Leave a Reply

Your email address will not be published. Required fields are marked *