Creating a singleton class with dispatch_once for class hierarchy
Unless you have a good reason, you should generally avoid subclassing singletons. It creates a very confusing situation. If you create a singleton MyClass
, can you then create a singleton FirstClass
? Since FirstClass
must always be useable anywhere MyClass
is usable (by Liskov), now there are three "singleton" MyClass
objects. Now ObjC is very loose with singletons, and that's a good thing, but this is still very strange.
OK, that said, what about your problem? First the solution, then the answer. The solution is that MyClass
probably shouldn't be a singleton, as discussed above. Get rid of getInstance
in the superclass and just define it in the subclasses.
The answer to what is happening is in your dispatch_once
. You're passing the same static once
token in all cases. dispatch_once
will run no more than one time ever for a given token. The only way around this is to pass different tokens for each class, and I don't know of a convenient way to do that without duplicating the dispatch_once code in each file. You could try to create different once
tokens for each subclass, but that's likely to be more trouble and code than just duplicating the sharedInstance
method.
BTW, don't call it getInstance
. "get" has special meaning in ObjC, and you don't mean that here, so it's confusing. This is typically called sharedInstance
, or better sharedSomething
where "something" is your class. If you really do mean that there should be a MyClass
and there should be a FirstClass
and there should be a SecondClass
, you can implement sharedInstance
in all three.