Overview
Singleton implementation is basically creating a single object for access throughout the application. It works on the global access principle. Singleton pattern is implemented by creating a class method that generates an instance of the class only if the one doesnot exists in the memory.
Just keep a note of that singleton instance should always be created carefully in a Multithreaded environment. So just be sure while creating a class that its method is accessible by one thread at a time otherwise there might be condition raised which can crashes your application during runtime. Moreover these bugs are very hard to find in the environment for iOS development.
Like other languages, we can create a singleton class in Objective-C which is pretty much required when you want to share the resources among different classes in the application.
The biggest example of the Singleton is APPDELEGATE of an iOS app which is shared globally across the application.
How to implement ?
Create a class. It might extend NSObject or any other class which can particularly provide the additional methods required as per your implementation.
#import <foundation/Foundation.h> @interface MyManager : NSObject { NSString *someProperty; } @property (nonatomic, retain) NSString *someProperty; + (id)sharedManager; @end
You create an a static method that return <id> back to the caller. <id> is the default datatype for all the objects in Objective C.
Now switch to your implementation file.
The Singleton can be implemented using a couple of ways.
One is the use of the GCD to create one and other is using the normal Objective-C syntax.
Using GCD:
#import "MyManager.h" @implementation MyManager @synthesize someProperty; #pragma mark Singleton Methods + (id)sharedManager { static MyManager *sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager; } - (id)init { if (self = [super init]) { someProperty = [[NSString alloc] initWithString:@"Default Property Value"]; } return self; } @end
Using Objective C Syntax:
+ (id)sharedManager { static MyManager *sharedMyManager = nil; @synchronized(self) { if (sharedMyManager == nil) sharedMyManager = [[self alloc] init]; } return sharedMyManager; }
Here the @synchronized is used to allow the code to be accessed by a single thread only. Else you can create a property with the atomic attribute to make it Thread Safe.
How to access the instance ?
You can access the static components using the class name.
MyManager *sharedInstance = [MyManager sharedManager];