Create a singleton and disallow extra instances from alloc and init
suggest changeA 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];
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents