Singletons, There Can Only Be One.

Often the topic of heated discussions, singletons actually can be fairly useful in the right situation. Though many view the “wasteful” nature of singletons as a deal-breaker, they are not always as evil as they’re made out to be.

What is a Singleton?


A singleton (or shared instance), is a class that is only ever initialized once (well, hopefully) and is persistent throughout an entire application’s lifecycle. In practice, different parts of an application can store and read data from a singleton without having to worry about managing separate instances. Naturally, you will not always need to be accessing a singleton. This is the basis of many people’s “wasteful” views on the subject. Because a singleton is persistent throughout an application’s lifecycle, it’s allocated memory will stay occupied until the application is terminated; regardless of if it’s being used or not. Though having un-used allocated objects is never a great thing, the advantages of an always up-to-date data “manager” can sometimes be worth the slight memory hit.

GCD to the Rescue!


I’m not going to delve into what GCD (Grand Central Dispatch) is, but it’s available as of iOS 4 and you should use it. GCD provides a thread-safe way to create singletons via it’s dispatch_once function. This ensures that the singleton is only initialized once, and controls access in a safe fashion. A singleton created with GCD is as follows:

static MyClass *sharedClass = nil;

+ (MyClass *)sharedInstance {

    static dispatch_once_t token;
    dispatch_once(&token, ^{
        sharedClass = [[MyClass alloc] init];
    }
    return sharedClass;

}

You can implement your init method like you normally would, setting up variables and loading initial data. The instance of this singleton class can be accessed from anywhere in your application by calling:

MyClass *c = [MyClass sharedInstance];

Kind of neat huh?

Conclusion


You really need to determine if there is a better way before using a singleton. In most cases, the “controller passes object to another controller” paradigm works perfectly fine. However, sometimes, and I mean sometimes, the singleton pattern can be the right choice.