Saturday 23 April 2016

Singleton in swift (Best way to create)

There are many approaches to create a singleton object. In Objective C we create a singleton object by using dispatch_once.

+(id)sharedInstance {
    static Shared *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    return shared;

Here dispatch_once method of GCD ensures that object is created only one time and also it is thread safe.

In swift  we can also use the same approach to create a singleton object but today we will learn the best approach to create it. The best approach is Swift is one line singleton.

class Shared: NSObject {

    static let sharedInstance = Shared()
    private override init() { }

You were thinking how only writing one line solves our problem. So the answer is when the lazy initialization of the static variable is created then it is initiated inside the dispatch_once block and that is thread safe and ensures that only one instance is created.

You can easily check that by applying the breakpoint and checking the queue. Here you can easily see that internally it is calling dispatch_once.

Note – Don’t forget to make the init as private as it will ensure that no object can be created outside. If anyone try to create the object of your shared class then it will gives you error.

That’s all, enjoy creating you singleton object.

If you face any issue or have any suggestions, please leave your comment.

No comments:

Post a Comment