Labels

January 7, 2014

Singleton Class in Objective-C/iOS


Background :~

Have you ever wanted to share data between views, but couldn't figure it out? Now, here's a solution called - Singleton Class.

Singletons is an easy way to share data and common methods within your entire application.

Singleton class is used when you need to ensure that only one instance of the class can be instantiated and you need a global access for that.

Singleton classes are an important concept to understand because they exhibit an extremely useful design pattern.

Examples in UIKit:

  1. [UIApplication sharedApplication] - return the single instance of the app.
  2. [NSFileManager defaultManager] - returns the single instance of the file manager.


Implementation :~

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+ (Utility *)sharedHandler ;


Utility.m

#import "Utility.h"

@implementation Utility

+ (Utility *)sharedHandler {
static dispatch_once_t onceToken;
static Utility *sharedHandler = nil;
dispatch_once(&onceToken, ^{
sharedHandler = [[self alloc] init];
});
return sharedHandler;
}


How to Use :~

Utility *singletonObject = [Utility sharedHandler];