Andrew
Andrew

Reputation: 16051

Subclasses of singleton not working together

I use this code to create subclasses which are individually singletons:

+(id)sharedManager {

    Class class = [self class];

    static SPPanelManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[class alloc] init];
    });

    return sharedManager;
}

And then in the .h of each subclass, there's this, with the name of the class as the return value:

+(SPWeatherManager *)sharedManager;

If these are used individually, they work perfectly, and launch their class as expected. If used together however, they all take the class of the first singleton generated.

How could i change this code so that the subclasses are all their own singletons?

Upvotes: 1

Views: 182

Answers (2)

ecotax
ecotax

Reputation: 1953

It seems your complicated construct did not confuse dispatch_once a bit.
As requested (that's what dispatch_once is for, after all), sharedManager is only assigned once.

Upvotes: 2

David Hoerl
David Hoerl

Reputation: 41632

You need to create multiple singletons. Change the class factory method to test for the class, and if the base class create/return one object, and if the subclass another. You need two dispatch once objects (typing this on an iPad, could do real code later). In a more general sense, you could use a mutable dictionary to hold the dispatch object and singleton, thus supporting a virtually unlimited number of subclasses, by getting the NSString name of the class and using it as the key.

Upvotes: 1

Related Questions