Create a singleton and disallow extra instances from alloc, init, and new

suggest change
// MySingletonClass.h
@interface MySingletonClass : NSObject

+ (instancetype)sharedInstance;

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

@end

// MySingletonClass.m

@implementation MySingletonClass

+ (instancetype)sharedInstance
{
    static MySingletonClass *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] init];
    });
    
    return _sharedInstance;
}
-(instancetype)init
{
    self = [super init];
    if(self)
    {
        //Do any additional initialization if required
    }
    return self;
}
@end

Feedback about page:

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



Table Of Contents