Singleton Pattern Objective-C
November 7, 2013
So you want to have a singleton object in you iOS/Mac app? This is actually really simple to achieve. I will not discuss cons and pros of the pattern itself. There is plenty of material on the internet on that topic. Let’s get started and do some coding.
- Create class for you singleton.
- Add class method to access shared instance of the object:
- Implement the class method:
The implementation is quite simple. The first thing I do is declare the static instance of the class itself. Note that this is not initialised at this point. If I initialised it in here I would loose the behaviour I want as each time the method is called new object would be allocated. The second variable I need is a dispatch_once_t token which is used to check if the following operation was previously executed. It is important to have it declared as static. Lack of it might lead to weird behaviour. Finally I use GCD in form of dispatch_once. It performs work synchronously and guarantees that whatever operation you specified in a block executes only once. In our case we initialise the GTTSingleton object. At the end of the method I return the singeltonInstance knowing that it was properly initialised.