Create a singleton and disallow extra instances from alloc and init

suggest change

A singleton can be written so callers must use the shared instance 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;
}

-(instancetype)initClass
{
    self = [super init];
    if(self)
    {
        //Do any additional initialization if required
    }
    return self;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"Not designated initializer"
                                   reason:@"Use [MySingletonClass sharedInstance]"
                                 userInfo:nil];
}
@end
/* The following line throws an exception
   with the reason "Use [MySingletonClass sharedInstance]"
   if you alloc/init directly instead of using sharedInstance. */
MySingletonClass *mySingletonClass = [[MySingletonClass alloc] init];

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents