Leela Prasad PENUMUTCHU

@pleelaprasad

Singleton Object Creation in swift

In swift(iOS), Singleton class will be instantiated only once and will be in memory through out the app life cycle. So we can say at any given point of time in the app life cycle only one instance of the singleton object is used and it provides a global access point to it from anywhere in your project.

So it has global access, if start using many singleton objects in the project, that will give us a lot of trouble. For example you have a singleton object to change the font of a particular screen in your app, it is impossible to know where that change has been triggered(from which controller) where you assign multiple fonts to singleton object in different controllers. This leads to a lot of bugs in the app.

Singletons obviously exist for a reason, and there are times when they are the perfect choice for you. If you need to control an access to a shared resource, like app settings, or the keychain, singletons are a perfect choice.

In order not to corrupt our data, we need to control the write access in the singleton. One of the ways we can do this is to raise a dispatch barrier. A dispatch barrier will ensure that a piece of code will be executed, and while it’s being executed, no other piece of code will be executed. This is very important. With this simple GCD flag, we’ll be able to solve our problems.

For example:

class MyClass {
private init() {}
public static let shared = MyClass()
func someFuntion() {
}
}

Creating a singleton like in the above example is fine and it is thread safe. It will be instantiated once and will be in memory all the time of app life cycle. Some times we do not use it, then what is it use by being in memory?. The downside of this approach is, the class get’s loaded in memory even if it’s never used.

Note that in the above example it has private initialiser, in order to restrict the object creation even accidentally in other parts of the app. This ensures us only one instance is there.

To load the singleton instance into the memory whenever we needed, we need to create it by using lazy keyword. Once it creates, it will reside in the memory till app terminates.

Assume the above singleton object is being accessed from two threads which are running slightly one after another. In this case the singleton object might have a chance to be created twice. So to solve this kind of duplications or multiple creations, we raise the barrier to stop all the currently running tasks while the object is being created. It ensures only one object will be created in the app at any situation in multi threading environment in iOS.

— — — — — — — — — *********************** — — — — — — — — —

If you like my tutorials please follow me on medium, twitter & linkedIn accounts.

Thanks for reading…

****************************!!!See you!!!****************************

More by Leela Prasad PENUMUTCHU

Topics of interest

More Related Stories