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:~

  • [UIApplication sharedApplication] – return the single instance of the app.
  • [NSFileManager defaultManager] – returns the single instance of the file manager.

Implementation:~

Utility.h
#import <Foundation/Foundation.h>

@interface Utility : NSObject

+ (instancetype)sharedInstance ;

Utility.m

#import "Utility.h"

@implementation Utility

#pragma mark - Singleton
+ (instancetype)sharedInstance {
    
    static id _sharedInstance = nil;
    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] init];
    });
    
    return _sharedInstance;
}

How to Use:~

Utility *singletonObject = [Utility sharedInstance];

This is the safest way to create a singleton and it is 100% thread safe.

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