Alex Rivera | Logout

What's the correct method to subclass a singleton class in Objective -C?

Asked 2010-08-03T06:25:01.083
14

I have created a singleton class and I want to create a class which is subclass of this singleton class, what is the correct method to do it

Edit
Report

1 Answer

0

I had a similar problem, I had multiple targets that needed to have a slightly different singleton implementations: each target would include the base class + a specific subclass. This was achieved by writing the base class like so:

+ (SingletonBaseClass*) sharedInstance {
    static SingletonBaseClass * sharedInstance = nil;
    if (!sharedInstance) {
        sharedInstance = [[[self class] alloc] init];
        [sharedInstance customInit];
    }
    return sharedInstance;
}

The key difference is [self class] instead of the actual class name. That way when the we call: [SingletonSubclass sharedInstance] the correct object is instantiated.

Please note that this is a specific case, in the general case I agree with previous answers.

answered 2012-09-19T10:09:52.683

Your Answer