Saturday, December 26, 2015

How can we achieve singleton pattern in iOS?

The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource.

Several Cocoa framework classes are singletons.
They include NSFileManager, NSWorkspace, NSApplication, and, in UIKit, UIApplication. A process is limited to one instance of these classes. When a client asks the class for an instance, it gets a shared instance, which is lazily created upon the first request.Refer: Singleton Pattern

Example:
Making singleton of MyClass

+ (instancetype)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}


//In Swift
class SomeManager {
    static let sharedInstance = SomeManager()
}