I have 2 child classes that inherit from MyClass, and each child class must be single.
I used this template to get a static instance when I don't have other classes that inherit:
+ (MyClass *)getInstance { static dispatch_once_t once; static MyClass *instance; dispatch_once(&once, ^{ instance = [[MyClass alloc] init]; }); return instance; }
It works just fine. Now, if I add two new child classes, FirstClass and SecondClass, both of which inherit from MyClass, how can I restore the corresponding ChildClass?
dispatch_once(&once, ^{ // No longer referencing 'MyClass' and instead the correct instance type instance = [[[self class] alloc] init]; }); FirstClass *firstClass = [FirstClass getInstance]; // should be of FirstClass type SecondClass *secondClass = [SecondClass getInstance]; // should be of SecondClass type
Doing the above means that I always return some class that I created 1st, as my type is the second class:
first: <FirstClass: 0x884b720> second: <FirstClass: 0x884b720> // Note that the address and type as identical for both.
What is the best way to create matching single single classes without adding the getInstance method to each of the child classes?
multithreading objective-c singleton class-hierarchy
Howard spear
source share