Friday, April 11, 2014

iOS Singleton Pattern Under ARC

Singleton Pattern is one of the most famous software design pattern being used in many softwares. It simply and surely always return the same one single instance of a class. It will provide the same instance for whoever need an instance of it.

Basically in Java, if you need a singleton class, you need to define a private static variable, which could be initialized and assigned once. Then, any time other class needs an instance of this class, this class will check if the static instance variable is null or not. If it's not null, return it. Otherwise, initialized and assign it. For more detail, I'd recommend the book <Head First Design Patterns>(This book's code is implemented in Java).

While the problem is how can we implement this design in Objective-C.

Here is the snippet of code.

+ (MyClass *)sharedInstance {
    static MyClass *sharedInstance;
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[MyClass alloc] init];
    return sharedInstance;

The Apple doc recommends the fowlloing way, which is the same as the one above:

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

No comments :

Post a Comment