I want to have a thread safe, ARC compatible singleton, but is seems to me that the most common example of singleton that I find, an example pasted here:
+ (MyClass *)sharedInstance
{
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
doesn’t stops other developer from calling [[MyClass alloc] init] and overriding the desired flow.
What is the proper way to handle it (apart from throwing exception in init)?
you also have to override the
+allocmethod to avoid to allocate more than one instance of the singleton.EDIT#3: well, I really know what the official documentation says about overriding the
+allocmethod, but to achieve the asked benefit there is no way to avoid it. personally I don’t agree to do it but it can provide the desired result.it would be like this:
EDIT #1
you don’t definitely need to throw an exception here but it is much more visual feedback for the developers of they use your class in wrong way, than sending back a simple
nilpointer.EDIT #2
I’ve added a simple trick to avoid the developers instantiate the class to bypass the modified
+allocmethod, in that case the allocation will work well but the-initwill throw an exception.