I have a class Parent and a class Child. Child derives from Parent. I only instantiate the Child class, the parent gets never initialized directly, only by the child.
I need at least Parent to be a singleton. If that does not work, Child being a singleton is okay too.
I tried the following but that didn’t change it to a singleton:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
The Child class calls [super init] to instantiate the Parent. Can you help me here?
EDIT: I add some background information for my solution (architecture): I have a web service client which has a connection to a web service. I have a base class (Parent) which has information about the connection (authenticated, how to connect etc) and I have different child classes which derive from this base class. The need for different child classes is that one child is responsible for a set of web service logic and another child is responsible for another set of web service logic. The problem is, I want the connection information to be singleton (because they all use only ONE connection, not many).
If I understand you correctly what you are asking doesn’t make sense, you seem to be confusing relationship with inheritance. If you have:
Then every
Childyou create is aParentas well, indivisibly part of itself, there is no way to split theParentfrom theChild– you have a single object. Using inheritance does not give you multiple children with a single shared parent.If you want many children to share a single parent then you need your
Childclass to have aParent. For example:used as:
If you wish you can make
Parenta singleton class (only one instance possible), or a shared instance class (one shared instance, other instances possible).With inheritance, as opposed to a relationship, it is hard (but not impossible ;-)) to derive from a true singleton class and if you do so the derived class is itself a singleton.
You can derive from a shared instance class; and you could write the class (hard again) so that you can have one and only one instance which is not indivisibly part of a instance of a derived class.
Note: the other answers so far have all provided you with code to produce a shared instance class, a true singleton class is a little more involved (you can find the code in Apple’s documentation) and often a shared instance class is sufficient.
HTH and I’ve haven’t misunderstood your question completely!