Looking for objective-c Answers? Try Ask4KnowledgeBase
Looking for objective-c Keywords? Try Ask4Keywords

Objective-C Language Singleton Class


Example

What is a Singleton Class?

A singleton class returns the same instance no matter how many times an application requests it. Unlike a regular class, A singleton object provides a global point of access to the resources of its class.

When to Use Singleton Classes?

Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

How to Create Singleton Classes

First, create a New file and subclass it from NSObject. Name it anything, we will use CommonClass here. Xcode will now generate CommonClass.h and CommonClass.m files for you.

In your CommonClass.h file:

#import <Foundation/Foundation.h>

@interface CommonClass : NSObject {
}
+ (CommonClass *)sharedObject;
@property NSString *commonString;
@end

In your CommonClass.m File:

#import "CommonClass.h"

@implementation CommonClass

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

- (id)init {
    if (self = [super init]) {
        self.commonString = @"this is string";
    }
    return self;
}

@end

How to Use Singleton Classes

The Singleton Class that we created earlier will be accessible from anywhere in the project as long as you have imported CommonClass.h file in the relevant module. To modify and access the shared data in Singleton Class, you will have to access the shared Object of that class which can be accessed by using sharedObject method like following:

[CommonClass sharedObject]

To read or modify the elements in Shared Class, do the following:

NSString *commonString = [[CommonClass sharedObject].commonString; //Read the string in singleton class

NSString *newString = @"New String";
[CommonClass sharedObject].commonString = newString;//Modified the string in singleton class