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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents