Creating Singleton…

Singleton classes are unique design patterns which are greatly used for storing data in memory for global use in the application. A Singleton class can have only one instance and that same instance is returned when the initializer is called. Generally the designated intializer (the initializer which makes the [super init] call) is internally called in a class method (initializer) which creates a static instance of the class and returns it. Generally this initializer is prefixed with “Shared” e.g. SharedManager etc.

Steps to Create Singleton

Let’s consider for a moment that we are going to create a singleton class named “MySingleton” and following are the exact steps you will need to follow in a ARC environment.

Step 1. Method and Property Declaration

  1. Declare the required properties in the header file
  2. Declare the initializer class method name

Code:

//MySingleton.h

@interface MySingleton : NSObject {
NSString *someProperty;
}

@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedMySingleton;

@end

Step 2. Method Implementation

Inside the class method sharedMySingleton –

  1. Declare a static variable named sharedMySingleton
  2. Use GCD command “dispatch_once_t” to call the designated initializer method once and assign the same to sharedMySingleton
  3. Return the static variable sharedMySingleton

Implement the designated initializer –

  1. Assign the [super init] to self as is done in designated initializers
  2. Initialize the variables declared in the header file

Code:

+ (id)sharedManager {
static MySingleton *sharedMySingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMySingleton = [[self alloc] init];
});
return sharedMySingleton;
}

– (id)init {
if (self = [super init]) {
someProperty = [[NSString alloc] initWithString:@”Default Property Value”];
}
return self;
}

This class will return the same instance when ever the “sharedMySingleton’” is called and you have got a Singleton!

Update: Mattt Thompson has put together a nifty little code snippet here for your Xcode to create Singleton classes.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s