Background
Singletons classes are an important concept to understand because they exhibit an extremtely useful design pattern.
This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.
How to implement
You can implement a singleton class in Objective-C using the following code:
MyManager.h
1 2 3 4 5 6 7 8 9 10 11 |
|
MyManager.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
What this does is it defines a static variable (but only global to this translation unit)) called sharedMyManager
which is then initialised once and only once in sharedManager
. The way we ensure that it’s only created once is by using the dispatch_once
method from Grand Central Dispatch (GCD). This is thread safe and handled entirely by the OS for you so that you don’t have to worry about it at all.
However, if you would rather not use GCD then you should use the following code for sharedManager
:
Non-GCD based code
1 2 3 4 5 6 7 |
|
Then you can reference the singleton from anywhere by calling the following function:
MyManager *sharedManager = [MyManager sharedManager];
I’ve used this extensively throughout my code for things such as creating a singleton to handle CoreLocation or CoreData functions.
Non-ARC code
Not that I recommend it, but if you are not using Automatic Reference Counting (ARC), then you should use the following code:
MyManager.h non-ARC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
1) How do I implement an Objective-C singleton that is compatible with ARC?
3) iOS | How - To Share Data Between View Controllers using a Singleton