I know there are several threads on this, but none answer my questions.
I've implemented my singleton class like this (being aware of the controversy about singletons):
+ (MyClass*) sharedInstance {
static MyClass *_sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[MyClass alloc] init];
});
return _sharedInstance;
}
- (instancetype)init{
self = [super init];
if (self) {
//setup code
}
return self;
}
I tried instantiating a different object and compared it to the one returned by sharedInstance with '==' and they were indeed different.
Questions:
- Shouldn't creating more than one object of the singleton class be impossible? Isn't that the point? Singleton implementation in Java prevents it.
- And if so, how? Should I make a setup method and call it instead of having the init implemented and doing it?
- Is this correct implementation?
You can't make the
init
method private, like you would do in Java with the constructor. So nothing stops you from calling[[MyClass alloc] init]
which indeed creates a different object. As long as you don't do that, but stick to thesharedInstance
method, your implementation is fine.What you could do: have the
init
method raise an exception (e.g. with[self doesNotRecognizeSelector:@_cmd]
) and perform the initialization in a different method (e.g.privateInit
) which is not exposed in the header file.