Objective-C Language Creating Singleton class and also preventing it from having multiple instances using alloc/init.


We can create Singleton class in such a way that developers are forced to used the shared instance (singleton object) instead of creating their own instances.

@implementation MySingletonClass

+ (instancetype)sharedInstance
    static MySingletonClass *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] initClass];
    return _sharedInstance;

    self = [super init];
        //Do any additional initialization if required
    return self;

- (instancetype)init
    @throw [NSException exceptionWithName:@"Not designated initializer"
                                   reason:@"Use [MySingletonClass sharedInstance]"
    return nil;

/*Following line will throw an exception 
  with the Reason:"Use [MySingletonClass sharedInstance]" 
  when tried to alloc/init directly instead of using sharedInstance */
MySingletonClass *mySingletonClass = [[MySingletonClass alloc] init];