A singleton class is a class that can only have one instance of the class at any given time.

You can create a singleton class in Objective-C by using the following template:

// MySingleton.h

#import

@interface MySingleton : NSObject

+ (instancetype)sharedInstance;

@end

// MySingleton.m

#import “MySingleton.h”

@implementation MySingleton

+ (instancetype)sharedInstance {
static MySingleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MySingleton alloc] init];
});
return sharedInstance;
}

@end

Leave a Reply

Your email address will not be published. Required fields are marked *